简体   繁体   English

动态加载JavaScript文件

[英]Load javascript files dynamically

I am trying to load a list of js files dynamically. 我正在尝试动态加载js文件列表。 Everything for the moment works fine. 目前一切正常。 The only problem is that I wrote my func inside the loop so my code will be repeated many times. 唯一的问题是我在循环内编写了func,因此我的代码将重复多次。 What I want to do is to make a loop to download the files and then confirm that they are already loaded and executed my func() . 我要做的是制作一个循环,以下载文件,然后确认它们已经加载并执行了我的func()

For my code if I write func() outside the loop I get an error message. 对于我的代码,如果我在循环外编写func()则会收到一条错误消息。 Mean outside onreadystate etc I get error message 意思是在onreadystate之外,我收到错误消息

   function( libs, func ){
            if( typeof func === 'function' ) {


                libs.forEach( function( fileName ) {

                    var script = document.createElement('script');
                    var head   = (document.getElementsByTagName("head")[0] || document.documentElement);
                    script.setAttribute("type", "text/javascript");

                    if (script.readyState){  //IE
                        script.onreadystatechange = function(){
                            if (script.readyState == "loaded" || script.readyState == "complete") {
                                script.onreadystatechange = null;
                                head.remove( script );
                                func();
                            }
                        };
                    } else {  //Others browsers
                        script.onload = function(){
                            head.remove( script );
                            loaded = true;
                            func();
                        };
                    }
                    script.setAttribute("src", fileName);
                    head.appendChild( script );

                });


            }
        }

do you realy need to load it by your own function? 您真的需要通过自己的功能加载它吗? Why don't you use a script loader like requirejs? 为什么不使用requireJS这样的脚本加载器?

Here you can find other: https://stackoverflow.com/questions/12779565/comparing-popular-script-loaders-yepnope-requirejs-labjs-and-headjs 在这里您可以找到其他: https : //stackoverflow.com/questions/12779565/comparing-popular-script-loaders-yepnope-requirejs-labjs-and-headjs

I'm not exactly sure that I understand correctly, but you want to execute your function when all files are downloaded? 我不确定我是否理解正确,但是要下载所有文件后执行功能吗? The most common way would be to have a counter. 最常见的方法是拥有一个柜台。 I used this function when doing something similar, which takes a function that can be executed after each file load, and one that is executed when all files are loaded. 我在执行类似操作时使用了此功能,该功能具有可以在每次加载文件后执行的功能,以及可以在加载所有文件后执行的功能。

I used the following function to keep track of the number of files loaded. 我使用以下函数来跟踪加载的文件数。

function loadJs(files, perFileCallback, doneCallback){
    var numFiles = files.length,
        numFilesLoaded = 0,
        loadedFiles = [],
        fileOrder = {};

    if(numFiles === 0){
        doneCallback([]);
        return;
    }

    function _loadFileCallback (file, fileName) {
        numFilesLoaded++;
        loadedFiles[fileOrder[fileName]] = file; // Must be placed in correct order.
        perFileCallback(numFilesLoaded);
        if (numFiles === numFilesLoaded && perFileCallback) {
            doneCallback(loadedFiles);
        }
    }

    for (var i = 0; i < files.length; i++) {
        fileOrder[files[i]] = i;
        _loadFile(files[i], _loadFileCallback); // Load the file with ajax and perform _loadFileCallback when done.
    }
}

You can also see all three functions I chained to use it on pastebin . 您还可以看到我链接在一起在pastebin上使用的所有三个功能。

It uses jQuery, but you can swap it with a normal ajax call if you desire. 它使用jQuery,但您可以根据需要将其与普通的ajax调用交换。

This also takes into account that when adding the files to your head, you do it in the correct order. 这还考虑到将文件添加到头部时,您以正确的顺序进行操作。 This was because I would have a file which defined var app, and one which defined app.mySite, and it was vital that app was defined before app.mySite could be created. 这是因为我将拥有一个定义var app的文件和一个定义app.mySite的文件,并且在创建app.mySite之前定义该应用程序至关重要。

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

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