2012-07-30 56 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 
}