如何强制JavaScript等待动态添加的脚本文件完成加载后?

时间:2012-07-16 21:35:02

标签: javascript jquery

我正在尝试编写一个将javascript文件附加到DOM的函数,但我希望其余的代码等到新添加的JS文件完全加载。以下是我要完成的示例,尽管此代码无法正常运行:

$(document).ready(function () {
    var newScript = document.createElement("script");
    newScript.setAttribute("type", "text/javascript");
    newScript.src = "http://www.domain.com/script.js";
    document.getElementsByTagName("body")[0].appendChild(newScript);
    $(newScript).ready(function () { // This is the idea of what I'm trying to do, but this doesn't seem to actually wait until the new file is completely loaded.
        foo.bar(); // foo is a new global variable which is declared in the newScript. This causes an error "foo is not defined".
        // Here is where more code I wish to execute should continue.
    });
});

4 个答案:

答案 0 :(得分:3)

Musa在上面的评论中提到过。使用jQuery' getScript并使用成功回调函数来触发其他函数。

答案 1 :(得分:1)

如果您想要更强大的模块加载功能,那么require.js在此容量下运行良好。请查看:http://requirejs.org/docs/why.html以获取概述。我专门为延迟加载脚本模块使用require.js。

答案 2 :(得分:1)

使用jQuery(正如你标记的那样),非常简单:

$.getScript('/script.js', function() {
    foo.bar();
});

答案 3 :(得分:0)

有几种不同的方法可以做到这一点......通过库或“手工”,可以说,只使用浏览器API和直接的JavaScript。有关如何仅在JS中执行此操作的答案,请在此处查看Stoyan's post以获取指导。基本上,它的要点是为脚本的unloadonreadystatechange属性设置事件处理程序,然后检查readyState是“已加载”还是“已完成”(如果是完全存在)。它看起来像这样:

var done = false;
newScript.onload = newScript.onreadystatechange = function () {
    if (!done && (!newScript.readyState || newScript.readyState === "loaded" || newScript.readyState === "complete)) {
        done = true;
        // run your actual code here
    }
};