Javascript multiple Dynamic Insertion

ぐ巨炮叔叔 提交于 2019-11-28 14:48:57

The context for how you use this loadScript function escapes me here and looks a lot more confusing than it probably needs to be.

If you want to load scripts in order, why don't you just make a list of them in the order you want to load them, load the first one. When it completes loading, update your list to remove the one that just loaded and load the next one, etc...

Here's some code that could do that and should work with either of the script load detection mechanisms that browsers use and will wait until the onload function is called (or readystatechange notification) until loading the next script:

function loadScriptsSequential(scriptsToLoad) {

    function loadNextScript() {
        var done = false;
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.onreadystatechange = function () {
            if (this.readyState == 'complete' || this.readyState == 'loaded') {
                scriptLoaded();
            }
        }
        script.onload = scriptLoaded;
        script.src = scriptsToLoad.shift(); // grab next script off front of array
        head.appendChild(script);

        function scriptLoaded() {
            // check done variable to make sure we aren't getting notified more than once on the same script
            if (!done) {
                script.onreadystatechange = script.onload = null;   // kill memory leak in IE
                done = true;
                if (scriptsToLoad.length != 0) {
                    loadNextScript();
                }
            }
        }
    }

    loadNextScript();
}

var scripts = [a,b,c,d,e,f];        // scripts to load in sequential order
loadScriptsSequential(scripts);

As others have mentioned, there are very helpful frameworks (like jQuery) that have built-in functions for loading scripts.

Why don't you just add the links to your javascript in the right order and then start using a javascript library like jQuery?

There is a "detecting load completion" method you could use. take a look at this link that demo's it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!