Dynamic, cross-browser script loading

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

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

3条回答
  •  既然无缘
    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);
    }
    

提交回复
热议问题