javascript 文件的同步加載與異步加載


HTML 4.01 的script屬性

charset: 可選。指定src引入代碼的字符集,大多數瀏覽器忽略該值。
defer: boolean, 可選。延遲腳本執行,相當於將script標簽放入頁面body標簽的底部,js腳本會在document的DOMContentLoaded之前執行。除IE和較新版本的Firefox外,其他瀏覽器並未支持。
language: 已廢棄。大部分瀏覽器會忽略該值。
src: 可選。指定引入的外部代碼文件,不限制后綴名。
type: 必選。指定腳本的內容類型(MIME類型)。現實中通常不指定該值也可以,瀏覽器會默認當作text/javascript類型來解釋執行。

 

HTML5中的script屬性:

script 標簽在HTML5中除了具備HTML5新標准定義的屬性以外,和HTML4.01相比移除了language屬性,修改了type屬性為可選的(默認text/javascript),並新增了一個屬性async。

async :boolean, 屬性的作用,定義腳本是否異步執行,取值true或false。

如果 async 設為 true ,會忽略 defer 屬性。

 

異步執行的 js 文件被假定為不使用 document.write()  向加載中的 document 寫入內容,因此不要在 異步執行的 js 文件的加載執行過程中使用 document.write()

 

除了 script 標簽屬性外,頁面引入 js 文件的方式影響其加載執行方式:

  • 任何以添加 script 節點(例如 appendChild(scriptNode) ) 的方式引入的js文件都是異步執行的 (scriptNode 需要插入document中,只創建節點和設置 src 是不會加載 js 文件的(IE6-9 除外),這跟 img 的預加載不能類比 )  ,無需特別設置script.type,如果過設置,需要設置為 javascript 類型,否則不會加載 js 文件(text/javascript ,或者帶版本號的,如果有特殊需求)
  • html文件中的<script>標簽中的代碼或src引用的js文件中的代碼是同步加載和執行的(較新的瀏覽器對阻塞的 js 可以並行加載了,但執行依然是同步的)
  • html文件中的<script>標簽中的代碼使用document.write()方式引入的js文件是異步執行的
  • html文件中的<script>標簽src屬性所引用的js文件的代碼內再使用document.write()方式引入的js文件是同步執行的
  • 使用 Image 對象異步預加載 js 文件(不會被執行,onload 事件不會觸發,但是會觸發onerror)

不要使用類似下面這種做法,這樣並不會發起加載 js 文件的請求:

divNode.innerHTML = '<script src="xxx.js"></script>';

window.onload 事件會在 js 文件加載完畢才觸發(即使是異步加載,還有 iframe 中網頁的加載  )

 

 

不管是script 標簽直接嵌入代碼還是引入js文件,  script 標簽的 js 代碼都是解析一段然后執行一段,因此不要出現類似  在前一個script 標簽的代碼中使用 變量,在后一個標簽的代碼中定義變量 這種錯誤的做法。

 

=====================================================

1、

<script>

//同步加載執行的代碼

</script>

2、

<script src="xx.js"></script>  //同步加載執行xx.js中的代碼

因為是同步的,可以使用document.wirte(), 比如 jsonp ,嵌入一個 js 文件,從服務器取數據並用服務器腳本輸出 js 代碼向 document 中寫入內容.

3、

<script>

document.write('<script src="xx.js"><\/script>');   //異步加載執行xx.js中的代碼

</script>

4、

<script src="xx.js"></script>

xx.js中有下面代碼:

document.write('<script src="11.js"><\/script>');   

document.write('<script src="22.js"><\/script>');   

則xx.js和11.js、22.js 都是同步加載和執行的。

如果 xx.js 、11.js 和 22.js 以插入 script 節點方式異步加載,則 11.js 和 22.js 是異步加載的,

如果 xx.js 以script 節點方式異步加載,  11.js 和 22.js 以 document.write(script) 方式加載,則 11.js 和 22.js 是同步加載的(經最新的瀏覽器測試, 在chrome 下,xx.j 異步加載執行已經無法使用 document.write() 向文檔寫入內容,不過如果不在document 加載過程插入,在插入之前使用 document.write() 開啟對頁面的重寫,則異步加載的 js 仍能寫入內容,比如頁面上一個 按鈕的 onclick 回調函數里面document.write(1),然后 headNode.appendChild(scriptNode) ,但是 firefox 和IE 卻可以在 document 關閉之前寫入(方法是在 xx.js中alert阻止文檔關閉))

測試:在11.js中 alert()(最好的方式是使用 服務器腳本輸出js代碼,在輸出前延遲 iao幾秒 , 比如  php : sleep(5) ;不要用 for 循環,js 引擎是單線程執行的,持續執行任何一段代碼都會導致其余代碼被阻塞)   , 22.js 中  console.log()  ,可以看到 22.js中的代碼被阻塞.

5、

下面這種方式,xx.js會在appendChild執行之后異步加載執行

var script = document.createElement("script");

script.setAttribute("src","xx.js");

documenrt.getElementsByTagName("head")[0].appendChild(script);

 

6、使用 Image 對象異步預加載 js 文件(不會被執行)

Image 的 src 被賦值時即發起請求,而且對文件類型不挑剔(圖片也可能是有腳本動態創建的,比如驗證碼),因此可以將 js 文件的 url 賦給 image.src, js 加載之后被瀏覽器緩存.

var img = new Image(); 
img.onload = function(){ alert(1); } ; //由於返回的js文件 MIME  不是圖片,onload回調函數並不會被觸發
img.src = 'http://localhost/test/loadjs/try.2.js';
var s = document.createElement("script");
var h = document.getElementsByTagName("head")[0];

//執行 js
s.src=img.src;
h.appendChild(s);

 在檢測 文件 加載完畢時有一點問題,可以使用非標准的 image.complete ,該屬性在 chrome 和 firefox 下只有文件加載過程中才是 false(即使onerror中也是true),而在IE9下在onload 后為 true,未開始加載、加載過程中、加載失敗 都是 false,在 IE8 及IE8 以下, onload 中仍然是 false ,需要設置延時檢測才能檢測到 true,另外,IE 的圖片對象在加載之后無論是否成功,會獲得一個占位符的圖片尺寸,可以通過這個尺寸來檢測是否已經完成加載過程的執行(無論 onerror 還是 onload)。

var im = new Image();
console.log([1,im.complete,im.width,im.readyState]);
im.onerror=im.onload = function(event){ 
    var e = event||window.event;
        var eventType = e.type;
        var host = this;
    console.log(['callback ',eventType ,host.complete,host.width,host.readyState]);
    setTimeout(function(){// for ie8-
        console.log(['callback delay ',eventType ,host.complete,host.width,host.readyState]);
    },100); 
}
im.src="http://seajs.org/dist/sea.js";
console.log([1,im.complete,im.width,im.readyState]);

 

在 IE 中 image 對象有 onreadystatechange 事件, 該事件僅在 成功加載圖片后執行,加載 js 文件不會觸發該事件

var im = new Image();
console.log([im.complete, im.readyState]); // false,uninitialized 
im.onreadystatechange = function(){ 
  console.log([im.complete, im.readyState]); //false,complete 
   setTimeout(function(){ 
          console.log([im.complete, im.readyState]); //true,complete 

    },100);
 }
im.src = "http://www.baidu.com/img/baidu_sylogo1.gif";

 

  

 一個加載 js 文件的 函數:

var loadJS = function(url,callback){  
var head = document.getElementsByTagName('head');  
if(head&&head.length){
head = head[0];
}else{
head = document.body;
}

var script = document.createElement('script');   

script.type = "text/javascript";   
head.appendChild( script);

script.onload = script.onreadystatechange = function(){
//script 標簽,IE 下有 onreadystatechange 事件, w3c 標准有 onload 事件     
//這些 readyState 是針對IE8及以下的,W3C 標准的 script 標簽沒有 onreadystatechange 和 this.readyState , 
//文件加載不成功 onload 不會執行,
//(!this.readyState) 是針對 W3C標准的, IE 9 也支持 W3C標准的 onload if ((!this.readyState) || this.readyState == "complete" || this.readyState == "loaded" ){ callback(); } }//end onreadystatechange }
 script.src = url;   

 

對於第4點的測試(同步加載)(其中插入 alert 很容易看到加載時的阻塞)

tryjs.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script src="tryjs.js" 
onload="if(!document.all){console.log('outer js callback, not IE');}" 
onreadystatechange="console.log('outer js callback ',this.readyState,' IE');"></script>


<body>

</body>
</html>

 

tryjs.js

console.log('write begin');
document.write('<script src="try.1.js" onreadystatechange="console.log(\'file 1 callback \',this.readyState,\' IE\');" onload="if(!document.all){console.log(\'file 1 callback,NOT IE \');}"><\/script>');
document.write('<script src="try.2.js" onreadystatechange="console.log(\'file 2 callback \',this.readyState,\' IE\');" onload="if(!document.all){console.log(\'file 2 callback,NOT IE \');}"><\/script>');
console.log('write finished');

 

try.1.js

console.log('loadjs 1 begin');
console.log('loadjs 1 finished');

 

 

try.2.js

console.log('loadjs 2 begin');
console.log('loadjs 2 finished');

 

 

測試結果(file 2 和 file 1 的 callback complete 在IE7\8\9次序不確定

IE 7:
日志: outer js callback loading IE 
日志: outer js callback loaded IE 
日志: write begin 
日志: write finished 
日志: outer js callback complete IE 
日志: file 1 callback loading IE 
日志: file 2 callback loading IE 
日志: loadjs 1 begin 
日志: loadjs 1 finished 
日志: loadjs 2 begin 
日志: loadjs 2 finished 
日志: file 2 callback complete IE 
日志: file 1 callback complete IE 


IE8:
日志: outer js callback loading IE 
日志: outer js callback loaded IE 
日志: write begin 
日志: write finished 
日志: outer js callback complete IE 
日志: file 1 callback loading IE 
日志: file 2 callback loading IE 
日志: loadjs 1 begin 
日志: loadjs 1 finished 
日志: loadjs 2 begin 
日志: loadjs 2 finished 
日志: file 2 callback complete IE 
日志: file 1 callback complete IE 

IE9:
日志: write begin 
日志: write finished 
日志: outer js callback complete IE 
日志: file 1 callback loading IE 
日志: file 2 callback loading IE 
日志: loadjs 1 begin 
日志: loadjs 1 finished 
日志: loadjs 2 begin 
日志: loadjs 2 finished 
日志: file 1 callback complete IE 
日志: file 2 callback complete IE 



FIREFOX:
write begin 
write finished
outer js callback, not IE
loadjs 1 begin
loadjs 1 finished
file 1 callback,NOT IE
loadjs 2 begin
loadjs 2 finished
file 2 callback,NOT IE


CHROME:
write begin     
write finished    
outer js callback, not IE    
loadjs 1 begin    
loadjs 1 finished    
file 1 callback,NOT IE 
loadjs 2 begin    
loadjs 2 finished    
file 2 callback,NOT IE

 

//=========幾個測試文件(這是最近另外測的)============

files in  /test/loadjs/

http://files.cnblogs.com/ecalf/loadjs.rar

 


免責聲明!

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



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