Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

javascript按顺序动态加载js文件 #8

Open
chenshenhai opened this issue Jun 10, 2016 · 0 comments
Open

javascript按顺序动态加载js文件 #8

chenshenhai opened this issue Jun 10, 2016 · 0 comments
Labels

Comments

@chenshenhai
Copy link
Owner

chenshenhai commented Jun 10, 2016

javascript按顺序动态加载js文件

js文件的动态加载一般是通过在HTML里面追加<script> 标签进行处理,但是有时候动态追加的几个js文件有先后的依赖顺序,例如a.js、b.js、c.js依次依赖,如果直接用追加<script>标签方法可能会导致先加载完c.js,但是a.js和b.js没加载完导致报错。

解决的按顺序动态加载js文件的方案是按顺序等待文件加载,依次等待上一个js文件加载完后再加载下一个文件

/**
 * Created by ChenShenhai on 2015/12/6.
 */

(function(){

    /**
     * js列表加载索引
     * @type {number}
     * @private
     */
    var _index = 0;

    /**
     * 加载js文件
     * @name loadJs
     * @param {String} url
     * @param {Function} callback   文件加载后回调时间
     */
    function loadJs(url, callback) {
        var _script = document.createElement('script');
        _script.src = url;
        success = success || function(){};

        if(navigator.userAgent.indexOf("MSIE")>0){
            _script.onreadystatechange = function(){
                if('loaded' === this.readyState || 'complete' === this.readyState){
                    callback();
                    this.onload = this.onreadystatechange = null;
                    this.parentNode.removeChild(this);
                }
            }
        }else{
            _script.onload = function(){
                callback();
                this.onload = this.onreadystatechange = null;
                this.parentNode.removeChild(this);
            }
        }
        document.getElementsByTagName('head')[0].appendChild(_script);
    }

    /**
     * 加载js文件列表
     * @name loadJsList
     * @param {Array} arr
     */
    function loadJsList( arr ) {

        if( _index > arr.length ) {
            loadJs(arr[_index], function(){
                _index ++;
                loadJs(arr[_index]);
            })
        }
    }

   window.loadJsList = loadJsList; 
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant