2011-05-09 137 views
0

我可以(使用JavaScript)检测JavaScript文件是否已经加载,如果没有,添加onload处理程序?脚本标签由第三方库动态添加,因此我无法自己动态插入它。检测JavaScript文件是否已加载到页面后加载

+1

[从动态加载的外部JavaScript文件访问变量]的可能的重复(http://stackoverflow.com/questions/5897414/accessing-a-variable-from-dynamically-loaded-external-javascript-file) – meouw 2011-05-09 13:45:00

+0

@不是,正如他所说的:“我无法自己动态地插入它” – gaRex 2011-05-09 17:37:35

回答

1

这是丑陋的解决方案,但可能:

function thirdPartyLoaded() { 
    // here we will have code, that will be executed, 
    // when 3rd party script will be loaded 
} 

// Also we know, that 3rd party have some global object or function 
// Let it be IAm3dPartyFunc for example 

// Then we somewhere add continuos watcher function with setInterval 
var watchFor3rd = setInterval(function(){ 
    if (undefined != IAm3dPartyFunc) { 
     thirdPartyLoaded(); 
     clearInterval(watchFor3rd); 
    } 
}, 500); 

这个函数会被每500毫秒(0.5秒),将检查,如果我们有一些全局对象/函数,是的3rdParty可能有。但是,如果第三方是由真正的gosu制作的,那么它就没有任何全球性的东西,因为所有的工作都可能在一些匿名的功能中,这个解决方案将不起作用。

你应该说明,你想使用哪个第三方,何时使用。