2012-07-30 57 views
1

我使用下面的JavaScript代碼,我試圖找出一旦文件被下載並添加到我的網頁的標題:加載JavaScript和檢查一旦加載

function loadjscssfile(filename, filetype) 
{ 
    if (filetype=="js"){ //if filename is a external JavaScript file 
     var fileref=document.createElement('script') 
      fileref.setAttribute("type","text/javascript") 
      fileref.setAttribute("src", filename) 
    } 
    else if (filetype=="css"){ //if filename is an external CSS file 
     var fileref=document.createElement("link") 
      fileref.setAttribute("rel", "stylesheet") 
      fileref.setAttribute("type", "text/css") 
      fileref.setAttribute("href", filename) 
    } 
    if (typeof fileref!="undefined") 
     document.getElementsByTagName("head")[0].appendChild(fileref) 
} 



loadjscssfile("jquery.js","js"); 

我通常使用下面的代碼,找出一旦我的形象已經加載:

document.getElementById("header_logo").src = "logo.png"; // load top logo 

var header_logo = document.getElementById("header_logo"); 
    header_logo.onload = function(e) { 
    // do something here, the file has loaded 
} 

,但我不知道如何檢查一次我的JS已加載..

任何想法?

(我不能使用jQuery)。

回答

1

你可以一個函數添加到onload事件:

function loadjscssfile(filename, filetype, onload) { 
    //if filename is a external JavaScript file 
    if (filetype == "js") { 
     var fileref = document.createElement('script'); 
     fileref.type = "text/javascript"); 
     fileref.onload = onload; 
     fileref.src = filename); 
     document.getElementsByTagName("head")[0].appendChild(fileref); 
     return; 
    } 

    //if filename is an external CSS file 
    if (filetype == "css") { 
     var fileref = document.createElement("link"); 
     fileref.rel = "stylesheet"; 
     fileref.type = "text/css"; 
     fileref.onload = onload; 
     fileref.href = filename; 
     document.getElementsByTagName("head")[0].appendChild(fileref); 
     return; 
    } 
} 



loadjscssfile("jquery.js","js", function() { alert(this.src); }); 
+0

我不會帶*的setAttribute *怕麻煩,乾脆直接設置屬性爲帶*的onload *屬性。但是許多瀏覽器不會爲腳本元素(例如IE 8)顯示加載事件。 – RobG 2012-07-30 04:14:17

+0

@RobG同意,只是不想混淆OP的代碼太多 – 2012-07-30 04:16:50

0

在HTML 4.01負載事件昂立通過bodyframeset元素的支持,雖然許多人支持它的img元素和一些腳本元素。

在HTML5中,script elementsbeforescriptexecuteafterscriptexecute載荷在相關時間在腳本元素的生命派出事件。但是,對於這些事件的支持很可能在許多正在使用的瀏覽器中不可用,因此不能被依賴。

查看腳本是否加載的最可靠的方法是測試變量的值,該變量的值由要執行的最後一位代碼賦值,例如,像最後陳述:

var loadedScripts = loadedScripts || {}; 
loadedScripts.fooScript = true; 

然後你就可以測試它:

if (loadedScripts.fooScript) { 
    // loaded 

} else { 
    // not loaded 
}