zoukankan      html  css  js  c++  java
  • js 动态加载js 并执行

        function loadJS(url, success) {
                var domScript = document.createElement('script');
                domScript.src = url;
                success = success || function () {};
                domScript.onload = domScript.onreadystatechange = function () {
                    if (!this.readyState || 'loaded' === this.readyState || 'complete' === this.readyState) {
                        success();
                        this.onload = this.onreadystatechange = null;
                        this.parentNode.removeChild(this);
                    }
                }
                document.getElementsByTagName('head')[0].appendChild(domScript);
            }
            loadJS("1.js");
        </script>

    转自  http://yijiebuyi.com/blog/2b23b571a0d5c94047f7e9c3150ac25d.html

    !function loadJS(){
        var jsFile = [
            {name:'file1',path:'js/file1.js',active:false,load:false},
            {name:'file2',path:'js/file2.js',active:false,load:false},
            {name:'file3',path:'js/file3.js',active:false,load:false},
            {name:'file4',path:'js/file4.js',active:false,load:false},
            {name:'file5',path:'js/file5.js',active:false,load:false}
        ]
        jsFile.forEach(function(item, index){
            if(localStorage['file_' + item.name]){
                item.load = true
                implementJS(item, index)
            }else{
                $.ajax({
                    type:"get",
                    url:item.path,
                    dataType:'text',
                    success:function(data){
                        item.content = data
                        item.load = true
                        implementJS(item, index)
                    }
                });
            }
        })
    
        function implementJS(item, index){
            //如果上一个文件已经执行了,则执行这个js文件
            if(index == 0 || jsFile[index - 1].active){
                storageJS(item, index)
                //尝试执行下一个js文件
                jsFile[index + 1] && jsFile[index + 1].load && implementJS(jsFile[index + 1], index + 1)
            }
        }
        function storageJS(item, index){
                //存储并执行js文件
                var name = 'file_' + item.name
                localStorage[name] = item.content || localStorage[name] || ''
                //这里要使用window.eval或者eval.call(window),否则eval里面的变量就不是全局变量
                window.eval(localStorage[name])
                item.active = true
        }
    }()

    //转自  https://segmentfault.com/a/1190000017548171

  • 相关阅读:
    编译安装php
    CentOS yum 安装LAMP PHP5.4版本
    CentOS下php安装mcrypt扩展
    CentOS安装crontab及使用方法(转)
    解决svn "cannot set LC_CTYPE locale"的问题
    CentOS下通过yum安装svn及配置
    linux svn启动和关闭
    vagrant启动报错The following SSH command responded with a no
    并行进程问题
    利用集群因子优化
  • 原文地址:https://www.cnblogs.com/enych/p/11805189.html
Copyright © 2011-2022 走看看