2014-01-13 57 views
0

在我的网站上包含/加载第三方小部件后,我在调用函数时遇到了一些问题。如何在异步JavaScript文件加载时调用函数?

请考虑这种情况。 我加载了一个脚本,它可以像这样从第三方库生成小部件。

<script> 
var element= document.createElement("script"); 
element.src = 'http://example.com/script.js'; 
document.body.appendChild(element); 
</script> 

完成装载后,它将创建#someElement div标签,其中有style属性有一些规则,并追加到body元素。

我想要做的是去除style属性并添加一些CSS类。

所以,问题是,我该如何检查,何时加载该文件,或该元素创建并在那之后调用我的函数?

谢谢!

回答

0

要检查脚本加载与否:

如果脚本在全球空间创建的任何变量或函数可以检查他们的所有脑干:

外部JS(全球范围) -

var myCustomFlag = true; 

并检查这已经运行:

if (typeof window.myCustomFlag == 'undefined') { 
    //the flag was not found, so the code has not run 
    $.getScript('<external JS>'); 
} 

你可以通过选择所有元素并检查其src属性来检查所述标签的存在:

//get the number of `<script>` elements that have the correct `src` attribute 
var len = $('script').filter(function() { 
    return ($(this).attr('src') == '<external JS>'); 
}).length; 

//if there are no scripts that match, the load it 
if (len === 0) { 
    $.getScript('<external JS>'); 
}Or you can just bake this .filter() functionality right into the selector: 

var len = $('script[src="<external JS>"]').length; 

进一步讨论。见:Verify External Script Is Loaded

相关问题