JavaScript異步加載與同步加載


關於同步加載與異步加載的區別

同步加載:同步模式,又稱阻塞模式,會阻止瀏覽器的后續處理,停止了后續的解析,因此停止了后續的文件加載(如圖像)、渲染、代碼執行。

異步加載:異步加載又叫非阻塞,瀏覽器在下載執行 js 同時,還會繼續進行后續頁面的處理。

為何使用異步加載原因:

優化腳本文件的加載提高頁面的加載速度,一直是提高頁面加載速度很重要的一條。因為涉及到各個瀏覽器對解析腳本文件的不同機制,以及加載腳本會阻塞其他資源和文件的加載,因此更多的采用異步加載。

使用異步加載的方式:

1.動態生成script標簽

加載方式在加載執行完之前會阻止 onload 事件的觸發,而現在很多頁面的代碼都在 onload 時還要執行額外的渲染工作等,所以還是會阻塞部分頁面的初始化處理

<!DOCTYPE html>
<html>
<head>
    <title>阻止onload事件的觸發</title>
</head>
<body>
    this is a test
    <script type="text/javascript">
        ~function() {
            //function async_load(){
                var s = document.createElement('script');
                s.src = 'http://china-addthis.googlecode.com/svn/trunk/addthis.js';
                document.body.appendChild(s);
            //}
            //window.addEventListener('load',async_load,false);
        }();
        // window.onload = function() {
           //  var txt = document.createTextNode(' hello world');
           //  document.body.appendChild(txt);
        //  };
    </script>
    <script type="text/javascript" src='http://libs.baidu.com/jquery/2.0.0/jquery.min.js'>    
    </script>
</body>
</html>

2.解決了阻塞 onload 事件觸發的問題

<!DOCTYPE html>
<html>
<head>
    <title>解決了阻塞onload事件觸發的問題</title>
</head>
<body>
    this is a test
    <script type="text/javascript">
        ~function() {
            function async_load(){
                var s = document.createElement('script');
                s.src = 'http://china-addthis.googlecode.com/svn/trunk/addthis.js';
                document.body.appendChild(s);
            }
            window.addEventListener('load',async_load,false);
        }();
        window.onload = function() {
            var txt = document.createTextNode(' hello world');
            document.body.appendChild(txt);
        };
    </script>
    <script type="text/javascript" src='http://libs.baidu.com/jquery/2.0.0/jquery.min.js'>    
    </script>
</body>
</html>

3.在支持async屬性的瀏覽器

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" async src='http://china-addthis.googlecode.com/svn/trunk/addthis.js'></script>
    <script type="text/javascript" async src='http://libs.baidu.com/jquery/2.0.0/jquery.min.js'></script>
    <title>使用async屬性</title>
</head>
<body>
    this is a test
</body>
</html>

補充:

DOMContentLoaded : 頁面(document)已經解析完成,頁面中的dom元素已經可用。但是頁面中引用的圖片、subframe可能還沒有加載完。

OnLoad:頁面的所有資源都加載完畢(包括圖片)。瀏覽器的載入進度在這時才停止。

圖解執行過程:

藍色線代表網絡讀取,紅色線代表執行時間,這倆都是針對腳本的;綠色線代表 HTML 解析。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM