网站动态加载JS脚本


Demo_1


function loadJS(url, fn) {
    var ss = document.getElementsByName('script'),
        loaded = false;
    for (var i = 0, len = ss.length; i < len; i++) {
        if (ss[i].src && ss[i].getAttribute('src') == url) {
            loaded = true;
            break;
        }
    }
    if (loaded) {
        if (fn && typeof fn != 'undefined' && fn instanceof Function) fn();
        return false;
    }
    var s = document.createElement('script'),
        b = false;
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('src', url);
    s.onload = s.onreadystatechange = function () {
        if (!b && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
            b = true;
            if (fn && typeof fn != 'undefined' && fn instanceof Function) fn();
        }
    };
    document.getElementsByTagName('body')[0].appendChild(s);
}


Demo_2


function JSLoad(args) {
    s = document.createElement("script");
    s.setAttribute("type", "text/javascript");
    s.setAttribute("src", args.url);
    s.onload = s.onreadystatechange = function () {
        if (!s.readyState || s.readyState == "loaded" || s.readyState == "complete") {
            if (typeof args.callback == "function") args.callback(this, args);
            s.onload = s.onreadystatechange = null;
            try {
                s.parentNode && s.parentNode.removeChild(s);
            } catch (e) {}
        }
    };
    document.getElementsByTagName("body")[0].appendChild(s);
}

posted @ 2019-01-02 12:04  sfornt  阅读(371)  评论(0编辑  收藏  举报