动态加载JS文件脚本

2019-06-04161次阅读javascript

通过监听load事件(IE是onreadystatechange)来确保js脚本加载完成可用:

function loadScript(url, callback){

    var script = document.createElement ("script");

    if (script.readyState){ //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" || script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else { //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;

    document.getElementsByTagName("head")[0].appendChild(script);
}

或者加载JS文件脚本后移除JS脚本 

function loadScript(url, callback){
    var doc = document;
    var head = doc.head || doc.getElementsByTagName('head')[0];
    var script = doc.createElement('script');
    script.src = url;
    //借鉴了jQuery的script跨域方法
    script.onload = script['onreadystatechange'] = function(){
        if((!this.readyState || this.readyState === "loaded" || this.readyState === "complete")){
            callback && callback();
            // 处理IE中的内存泄漏
            script.onload = script['onreadystatechange'] = null;
            if ( head && script.parentNode ) {
                head.removeChild( script );
            }
        }
    };
    //使用insertbefore而不是appendchild来规避IE6错误.
    head.insertBefore( script, head.firstChild );
}

如有需要你还可以使用$script.js-异步JavaScript加载程序和依赖关系管理器

上一篇: display:none及textarea实现按需加载、延迟加载、懒惰渲染  下一篇: inline-source把css、js代码内联插入到HTML中  

动态加载JS文件脚本相关文章