用javascript动态加载javascript脚本/css样式表

用javascript动态加载javascript脚本/css样式表
 
//   命名空间对象
    Namespace = new Object();
    Namespace.register = function(fullname) {
        try {
            var nsArray = fullname.split(".");
            var strNS = "";
            var strEval = "";
            for (var i = 0; i < nsArray.length; i++) {
                if (strNS.length > 0)
                    strNS += ".";
                strNS += nsArray[i];
                strEval += " if(typeof(" + strNS + ") =='undefined') " + strNS + " = new Object(); ";
            }
            if (strEval != "") eval(strEval);
        } catch (e) { alert(e.message); }
    }

    //注册命名空间 
    Namespace.register('Common');    
    /**动态加载资源文件(js 文件和 css 文件)**/
    Common.srcLoader = {
    /**入口函数**/
    /* fileList: 	 需要动态加载的资源列表 */
    /* callback: 	 所有资源都加载完后调用的回调函数,通常是页面上需要onload就执行的函数 */   
    /* scope: 	 	 作用范围 */
、、/* preserveOrder: 	 是否保持脚本顺序 */
        
        Load: function(fileList, callback, scope, preserveOrder) {
        var scope = scope || this,
            //var scope=this,//默认作用范围是当前页面
                head = document.getElementsByTagName("head")[0],
	            fragment = document.createDocumentFragment(),
                numFiles = fileList.length,
                loadedFiles = 0;

            // Loads a particular file from the fileList by index. This is used when preserving order
            var loadFileIndex = function(index) {
                head.appendChild(
                    Common.srcLoader.buildScriptTag(fileList[index], onFileLoaded)
                );
            };

            /**
            * 调用回调函数,当所有文件都加载完后调用
            */
            var onFileLoaded = function() {
                loadedFiles++;
                //如果当前文件是最后一个要加载的文件,则调用回调函数,否则加载下一个文件
                if (numFiles == loadedFiles && typeof callback == 'function') {
                    callback.call(scope);
                } else {
                    if (preserveOrder === true) {
                        loadFileIndex(loadedFiles);
                    }
                }
            };

            if (preserveOrder === true) {
                loadFileIndex.call(this, 0);
            } else {
                for (var i = 0, len = fileList.length; i < len; i++) {
                    fragment.appendChild(this.buildScriptTag(fileList[i], onFileLoaded));
                }
                head.appendChild(fragment);
            }
        },  
        
        //构造javascript和link 标签
        buildScriptTag: function(filename, callback) {
            var exten = filename.substr(filename.lastIndexOf('.') + 1);        
            if (exten == 'js') {
                var script = document.createElement('script');
                script.type = "text/javascript";
                script.src = filename;
                //IE has a different way of handling <script> loads, so we need to check for it here
                if (script.readyState) {
                    script.onreadystatechange = function() {
                        if (script.readyState == "loaded" || script.readyState == "complete") {
                            script.onreadystatechange = null;
                            callback();
                        }
                    };
                } else {
                    script.onload = callback;
                }
                return script;
            }
            if (exten == 'css') {
                var style = document.createElement('link');
                style.rel = 'stylesheet';
                style.type = 'text/css';
                style.href = filename;
                callback();
                return style;
            }
        }
    }
使用:在页面上使用
引用以上脚本是必须的让后在页面上加入 类似的代码:

<script type="text/javascript">
        //根据需要加载js文件,并设置回调函数
        Common.srcLoader.Load(
            [
                '../js/jquery.js',
                 '../js/ext-base.js',
                 '../js/ext-all.js',
                 '../js/ext_ux.js',
                 '../js/FBaseFunc.js',
                 '../js/FBaseJQueryFunc.js',
                 '../js/FBaseExtFunc.js',
                 'js/SchoolGradeTestCountDrillable.js',
                 '../js/lovcombo.js',
                 '../RptService/amchart/swfobject.js'
            ],
            loadPage,
            null,
            true
            );
            
        //回调函数
        function loadPage() {

            //设置全局相对路径
            gRPath = "../"
            target = "amcharts_1302230008081";
            reportID = "1";
            userID = "1";

            Ext.onReady(function() {
                //设置Cookie操作对象
                Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

                //标题区域
                var oleTitleInfo = new Ext.BoxComponent({ el: 'div_func_title', height: 50, region: "north" });
                DoSomething();

            });
        }
    </script>

动态加载脚本最大的好处在于减少页面初始化的响应时间,避免不需要加载外部 javascript

posted on 2011-06-21 17:02  黑头  阅读(1041)  评论(1编辑  收藏  举报

导航