有些时候我们需要动态的加载一些JS,并在JS加载完成后执行一些回调函数。
var loadscript = {
    $$: function (id) {
        return document.getElementById(id);
    },
    tag: function (element) {
        return document.getElementsByTagName(element);
    },
    ce: function (element) {
        return document.createElement(element);
    },
    js: function (url, callback) {
        var s = loadscript.ce('script');
        s.type = "text/javascript";
        s.src = url;
        if (document.documentMode == 10 || document.documentMode == 9) {
            s.onerror = s.onload = loaded;
        } else {
            s.onreadystatechange = ready;
            s.onerror = s.onload = loaded;
        }
        loadscript.tag('head')[0].appendChild(s);

        function ready() { /*IE7.0/IE10.0*/
            if (s.readyState == 'loaded' || s.readyState == 'complete') {
                callback();
            }
        }
        function loaded() { /*chrome/IE10.0*/
            callback();
        }
    }
};


//加载百度的uaredirect.js,回调执行uaredirect函数

loadscript.js("http://siteapp.baidu.com/static/webappservice/uaredirect.js", function() {
    uaredirect("https://m.baidu.com/");
});
参考网址:
http://www.cnblogs.com/jyk/archive/2013/05/14/3078024.html
http://www.cnblogs.com/w-y-f/p/3469211.html
http://www.xiariboke.com/design/2857.html

 

 

posted on 2017-01-17 20:07  怀素真  阅读(578)  评论(0编辑  收藏  举报