Dynamic, cross-browser script loading

前端 未结 3 1421
我在风中等你
我在风中等你 2020-12-05 15:25

I know that IE doesn\'t have a load event for

相关标签:
3条回答
  • 2020-12-05 16:07

    I want to add that if you don't support IE7 and below, you don't need onreadystatechange stuff. Source: quircksmode.org

    Simplified and working code from original answer:

    function scriptTag (src, callback) {
    
       // src is just a string now!
    
        var s = doc.createElement('script');
        s.type = 'text/javascript';
        s.src = src;
        s.async = false;
        s.onload = callback;        
        document.body.appendChild(s);
    }
    
    0 讨论(0)
  • 2020-12-05 16:17

    This is just an extension of ilia's answer. I used scriptTag like this: Works great:

        // these 3 scripts load serially.
    
        scriptTag(boot_config.DEPENDENCIES.jquery,function(){
            // jquery ready - set a flag
            scriptTag(boot_config.DEPENDENCIES.jqueryui,function(){
                // jqueryui ready - set a flag
                scriptTag(boot_config.DEPENDENCIES.your_app,function(){
                    // your_app is ready! - set a flag
                });
            });
        });
    
        // these 2 scripts load in paralell to the group above
    
        scriptTag(boot_config.EXTERNALS.crypto,function(){
            // crypto ready - set a flag
        });
    
        scriptTag(boot_config.EXTERNALS.cropper,function(){
            // cropper ready - set a flag
        });
    
    0 讨论(0)
  • 2020-12-05 16:19

    You can use a script loader like head.js. It has its own load callback and it will decrease load time too.


    From the headjs code: (slightly modified to be more portable)

    function scriptTag(src, callback) {
    
        var s = document.createElement('script');
        s.type = 'text/' + (src.type || 'javascript');
        s.src = src.src || src;
        s.async = false;
    
        s.onreadystatechange = s.onload = function () {
    
            var state = s.readyState;
    
            if (!callback.done && (!state || /loaded|complete/.test(state))) {
                callback.done = true;
                callback();
            }
        };
    
        // use body if available. more safe in IE
        (document.body || head).appendChild(s);
    }
    
    0 讨论(0)
提交回复
热议问题