3

我正在尝试编写一个将 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

4 回答 4

3

正如穆萨在上面的评论中提到的那样。使用 jQuery 的getScript并使用成功回调函数来触发您的其他函数。

于 2012-07-16T21:43:03.627 回答
1

如果你想要更健壮的模块加载功能,那么 require.js 在这种能力上效果很好。查看:http ://requirejs.org/docs/why.html以获得概述。我使用 require.js 专门用于延迟加载脚本模块。

于 2012-07-16T21:43:11.480 回答
1

使用 jQuery(如您所标记的),这非常容易:

$.getScript('/script.js', function() {
    foo.bar();
});
于 2012-07-16T21:43:50.450 回答
0

有几种不同的方法可以做到这一点......通过库或“手动”,可以这么说,只使用浏览器 API 和直接的 JavaScript。有关如何仅在 JS 中执行此操作的答案,请在此处查找Stoyan 的帖子以提供指导。基本上,它的要点是为脚本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
    }
};
于 2012-07-16T21:42:22.457 回答