如何等待脚本节点完成加载

How to wait for a script node to finish loading?

本文关键字:节点 加载 脚本 何等待 等待      更新时间:2023-09-26

在javascript中,我将<script tag>插入iframe:

var iframe = document.getElementById('iframe');
var doc= iframe.contentWindow.document.getElementsByTagName('head')[0];
var jquery = document.createElement("script");
jquery.type = "text/javascript";
jquery.src   = "jquery-1.9.1.min.js";
var script   = document.createElement("script");
script.type  = "text/javascript";
script.src   = "blah.js";
doc.appendChild(jquery);
doc.appendChild(script);

然而,blah.js中有jquery代码,有时这个脚本会失败,因为jquery脚本还没有完成加载。有办法等到它完成加载吗?

谢谢。

关键是使用script.onload = functionName;修复IE8。完整的代码请参见https://stackoverflow.com/a/15437678/2227298。

一旦jQuery加载,你可以使用jQuery.getScript与成功参数

在第一个脚本的末尾添加一个回调。

jquery.js:

if (window.jqueryLoaded)
    window.jqueryLoaded();

在你的代码:

// create the function that will be called once jquery finishes loading
function jqueryLoaded()
{
    doc.appendChild(blah);
}
// load jquery
doc.appendChild(jquery);

如果不能修改jquery.js文件,可以使用计时器:

var checkjQuery = window.setInterval(function() {
    if (!window.jQuery)
        return;
    window.clearInterval(checkjQuery);
    window.jqueryLoaded();
}, 10);