码迷,mamicode.com
首页 > Web开发 > 详细

动态添加JS文件到页面

时间:2015-08-25 19:18:10      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

 

/***
** 功能:  加载外部JS文件,加载完成后执行回调函数callback
***/
var utools = {
    config: {
        id: "",
        url: "",
        charset: "gb2312",
        callback: function () { }
    },
    merge: function (a, c) {
        for (var b in c) a[b] = c[b];
        return a
    },
    getScript: function (a) {
        var r = Math.floor(Math.random() * 10000);
        this.config = this.merge(this.config, a);
        var callback = this.config.callback;
        var scriptNode = document.createElement("script");
        scriptNode.setAttribute("id", this.config.id);
        scriptNode.setAttribute(‘charset‘, this.config.charset);
        scriptNode.setAttribute(‘type‘, ‘text/javascript‘);
        scriptNode.setAttribute(‘src‘, this.config.url + "?r=" + r);
        var head = document.getElementsByTagName("head")[0];
        head.appendChild(scriptNode);
        scriptNode[document.all ? "onreadystatechange" : "onload"] = function () {
            if (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") {
                if (callback) callback();
                scriptNode.onreadystatechange = scriptNode.onload = null;
                scriptNode.parentNode.removeChild(scriptNode)
            }
        };
    }
}

//调用方式
utools.getScript({url:"js文件路径"});


动态添加JS文件到页面

标签:

原文地址:http://www.cnblogs.com/allen-tech/p/4758234.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!