简体   繁体   中英

Load javascript files dynamically

I am trying to load a list of js files dynamically. 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. 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() .

For my code if I write func() outside the loop I get an error message. Mean outside onreadystate etc I get error message

   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?

Here you can find other: 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 .

It uses jQuery, but you can swap it with a normal ajax call if you desire.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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