简体   繁体   English

如何在JavaScript中的特定行上动态加载文件?

[英]How to dynamically load a file on a specific line in JavaScript?

I created this script for a core.js file for my client's website and I want to dynamically load a few javascript libraries from that core.js file. 我为客户网站的core.js文件创建了此脚本,我想从该core.js文件动态加载一些JavaScript库。 However, javascript libraries require that you load that library first , then use the rest of your script, because you have to define your libraries object before calling it, doh. 然而,JavaScript库要求您加载该库,然后用你的脚本的其余部分,因为你必须定义调用它,卫生署在你的库对象。 So I have this very simple script to dynamically load a file, but I want to know if there's a method to make sure that it loads it in priority ahead of the core.js file. 因此,我有一个非常简单的脚本来动态加载文件,但是我想知道是否有一种方法可以确保它在core.js文件之前优先加载它。 Here's the current script: 这是当前的脚本:

(function() {
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", "http://modernizr.com/downloads/modernizr-latest.js");
    if(typeof script != "undefined") {
        document.getElementsByTagName("head")[0].appendChild( script );
    }
})();

And in the debugger, you see: 在调试器中,您将看到:

Of course, it's going to load the dynamic file ahead of the core file, but I was wondering if there was a way to specify the line on the document for which to load the modernizr file? 当然,它将在核心文件之前加载动态文件,但是我想知道是否有一种方法可以指定文档上要加载modernizr文件的行? Otherwise, I can't use Modernizr, even though I have loaded it. 否则,即使已加载Modernizr,也无法使用它。

Obviously, I can't use jQuery, because I want to load that, too. 显然,我不能使用jQuery,因为我也想加载它。

You can respond to the loading of a dynamically-loaded JavaScript resource (or any resource, for that matter -- image, iframe, video, etc.) with a load event listener. 您可以使用load事件侦听器响应动态加载的JavaScript资源(或任何资源,例如图像,iframe,视频等)的load The easiest way to do it here would be: 最简单的方法是:

(function() {
    var script = document.createElement("script");
    ...
    script.onload = function() {
        // this will run later, when the script loads
        // in this function you can safely use Modernizr
    }
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM