best way of dynamic script loading

后端 未结 4 1030
耶瑟儿~
耶瑟儿~ 2020-12-17 02:13

I need to load some js files dynamically and sequentially(i.e. second script loads after load complete of first one, third after second and so on).

Question: how to

相关标签:
4条回答
  • 2020-12-17 02:26

    RequireJS:

    ... is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

    Says it is IE 6+, Firefox2 2+, Safari 3.2+, Chrome 3+ and Opera 10+ compatible.

    0 讨论(0)
  • 2020-12-17 02:34

    I think what you need is jQuery.getScript

    The function takes a URL and a success method with which you can chain loading of scripts and therefore load them sequentially:

    jQuery.getScript( url, function() { 
      jQuery.getScript( url2, function() 
        {/*... all 2 scripts finished loading */}
      );
    });
    
    0 讨论(0)
  • 2020-12-17 02:50

    Here is my snippet for loading several scripts using jQuery.getScript();

    function getScripts(inserts, callback)
    {
        var nextInsert = inserts.shift();
        if (nextInsert != undefined)
        {
            console.log("calling"+nextInsert);
        jQuery.getScript(nextInsert, function(){ getScripts(inserts, callback); })
                .fail(function(jqxhr, settings, exception){alert("including "+nextInsert+" failed:\n" +exception)});
        }
        else
        {
            if (callback != undefined) callback();
        }
    };
    

    Usage:

    var includes = [
        "js/script1.js",
        "js/script2.js",
        "js/script3.js"
    ];
    
    getScripts(includes, function(){ /* typically a call to your init method comes here */; });
    
    0 讨论(0)
  • 2020-12-17 02:53

    In Chrome, we can use onload and onerror to replace onreadystatechange.

    0 讨论(0)
提交回复
热议问题