常用js,css文件统一加载方法,并在加载之后调用回调函数

原创内容,转载请注明出处!

为了方便资源管理和提升工作效率,常用的js和css文件的加载应该放在一个统一文件里面完成,也方便后续的资源维护。所以我用js写了以下方法,存放在“sourceController.js”文件内。

/**
 * Created by MingChen on 2016/11/3.
 */
function sourceController() {
    this.root = "";

    this.callfunc = null; // 回调函数

    this.css = [];

    this.script = [];

    // css数量,兼容safari用
    var cssCount = document.styleSheets.length;

    // timeOut
    var tmpTimeOut = [];

    // 时间戳
    var startTime = null;

    /**
     * 设置文件根目录
     * @param url 根目录地址
     */
    this.setRoot = function (url) {
        this.root = url;
    };

    /**
     * 设置回调函数
     * @param func 回调函数
     */
    this.setCallBack = function (func) {
        this.callfunc = func;
    };

    /** 添加Script文件 请在addSource钱调用
     * @param url script文件路径
     */
    this.addScript = function (url) {
        if (url === "" || url == null) return;
        this.script.push(url);
    };

    /**
     * 添加CSS文件 请在addSource钱调用
     * @param url css文件路径
     */
    this.addCss = function (url) {
        if (url === "" || url == null) return;
        // console.log("csslength:" + this.css.length);
        this.css.push(url);
    };

    /** 添加常用资源 */
    this.addSource = function () {
        addMeta([["name", "renderer"], ["content", "ie-comp"]]);

        createCss(this);
    };

    /**
     * 添加<link> 默认先加载css
     * @param obj 当前对象
     */
    function createCss(obj) {
        // 如果没有css文件,不加载
        if (obj.css.length <= 0) return;
        var url = obj.css.shift();
        // console.log(url);
        var css = document.createElement("link");
        css.setAttribute("rel", "stylesheet");
        if (obj.root != "") {
            url = obj.root + "/" + url;
        }
        css.href = url;

        // 老版本safari特殊处理,获取浏览器信息的方法请自己添加
        if (browserInfo().browser == "safari" && parseInt(browserInfo().version) < 6) {
            var timer = setInterval(function () {
                // console.log("timer cssCount:" + cssCount + " len:" + document.styleSheets.length);
                clearTmpTimeOut();
                if (document.styleSheets.length == cssCount && obj.css.length > 0) {
                    addTask(createCss, 0, obj);
                } else if (document.styleSheets.length == cssCount) {
                    // 如果有js文件,开始加载js
                    if (obj.script.length > 0) {
                        addTask(createJs, 0, obj);
                    } else {
                        obj.css.length = 0;
                        if (typeof obj.callfunc == "function") {
                            obj.callfunc();
                        }
                    }
                    clearInterval(timer);
                }
            }, 50);
        } else {
            css.onload = function () {
                clearTmpTimeOut();
                if (obj.css.length > 0) {
                    addTask(createCss, 0, obj);
                } else {
                    // 如果有js文件,开始加载js
                    if (obj.script.length > 0) {
                        addTask(createJs, 0, obj);
                    } else {
                        tmpTimeOut.length = 0;
                        obj.css.length = 0;
                        if (typeof obj.callfunc == "function") {
                            obj.callfunc();
                        }
                    }
                }
            };
        }
        document.getElementsByTagName("head")[0].appendChild(css);
        cssCount++;
    }

    /**
     * 添加<script> js加载完后执行回调函数
     * @param obj 当前对象
     */
    function createJs(obj) {
        // 如果没有js文件,不加载
        if (obj.script.length <= 0) return;
        var script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('src', (obj.root) ? (obj.root + "/" + obj.script.shift()) : (obj.script.shift()));
        script.onload = script.onreadystatechange = function () {
            if (script.ready) {
                return false;
            }
            if (!script.readyState || script.readyState == "loaded" || script.readyState == 'complete') {
                script.onload = script.onreadystatechange = null;
                script.ready = true;
                clearTmpTimeOut();
                // console.log("time:" + (new Date().getTime() - startTime) + "ms " + script.getAttribute("src"));

                if (obj.script.length > 0) {
                    addTask(createJs, 0, obj);
                } else {
                    tmpTimeOut.length = 0;
                    obj.script.length = 0;
                    // 如果有回调函数 执行回调函数
                    if (typeof obj.callfunc == "function") {
                        obj.callfunc();
                    }
                }
            }
        };
        startTime = new Date().getTime();
        document.getElementsByTagName("body")[0].appendChild(script);
    }

    /**
     *添加一个任务,
     *    @param {Function} fun 任务函数名
     *    @param {number} delay 定时时间
     *    @param {object} params 传递到fun中的参数
     */
    function addTask(fun, delay) {
        var to = null;
        if (typeof fun == 'function') {
            var argu = Array.prototype.slice.call(arguments, 2);
            var f = (function () {
                fun.apply(null, argu);
            });
            to = window.setTimeout(f, delay);
            tmpTimeOut.push(to);
            return to;
        }
        to = window.setTimeout(fun, delay);
        tmpTimeOut.push(to);
    }

    // 清空加载计时器
    function clearTmpTimeOut() {
        while (tmpTimeOut.length > 0){
            var tto = tmpTimeOut.shift();
            window.clearTimeout(tto);
            tmpTimeOut.length = 0;
        }
    }
}

设置资源路径管理文件config.js。

/**
 * Created by MingChen on 2016/10/25.
 */
var sourcePath = {
    "iconfont": "css/iconfont/iconfont.css",
    "jquery": 'javascript/libs/jquery/jquery.js',
    "pieJS": "javascript/libs/PIEJS/PIE.js",
    "data": "javascript/publicData.js",
    // jquery-ui
    "cjqueryui": "css/jquery-ui.css",
    "jqueryui": 'javascript/libs/jquery/jquery-ui-1.11.4.js',
    // jqgrid
    "cjqgrid": "javascript/libs/jqgrid/ui.jqgrid.css",
    "jqgridcn":  "javascript/libs/jqgrid/grid.locale-cn.js",
    "jqgrid": "javascript/libs/jqgrid/jquery.jqGrid.js",
    // common
    "ccommon": "css/common.css",
    "common": "javascript/common.js",
    // header
    "cheader": "javascript/libs/headerMenu/css/headerMenu.css",
    "header": "javascript/libs/headerMenu/js/headerMenu.js",
    // circle
    "circle": "javascript/libs/raphael/cycle.js",
    "circleBar": "javascript/libs/raphael/raphael.js",
    // search
    "csearch": "javascript/libs/searchForm/css/searchForm.css",
    "search": "javascript/libs/searchForm/js/searchForm.js",
    // datePicker
    "datePicker": "javascript/libs/My97DatePicker/WdatePicker.js",
    // select2
    "cselect2": "javascript/libs/select2/css/select2.min.css",
    "select2min": "javascript/libs/select2/js/select2.min.js",
    "select2Func": "javascript/libs/select2/js/select2Func.js",
    // validator
    "cvalidator": "javascript/libs/validation/css/jqvForm.css",
    "validator": "javascript/libs/validation/js/jquery.validate.js",
    // dialog
    "cdialog": "javascript/libs/dialogBox/css/dialogBox.css",
    "dialog": "javascript/libs/dialogBox/js/dialogBoxUtils.js",
    // layer
    "clayer": "javascript/libs/layer/skin/layer.css",
    "layer": "javascript/libs/layer/layer.js"
};

在需要引入的页面只需要在<head>加入如下代码就可以一下子引入所有的常用资源了。为了显示美观在所有布局完成之间body设置visibility为hidden,布局完成后显示出来。

window.onload = function(){
    var sc = new sourceController();
    sc.setRoot("根目录地址");
    sc.css = [sourcePath.cjqueryui, sourcePath.cjqgrid];
    sc.script = [sourcePath.common, sourcePath.jquery, sourcePath.jqueryui, sourcePath.jqgrid];
    if(判断条件) // 根据需要额外添加的文件{ 
        sc.addCss("css/index.css"); // 额外添加的css文件,必须在加载资源之前加入
        sc.addScript("javaScript/index.js"); // 额外添加的js文件,必须在加载资源之前加入
    }
    sc.setCallBack(function(){
        document.body.style.display = "block"; // 显示body
    });
    sc.addSource(); // 加载常用的js和css文件
};

 

posted @ 2016-09-10 21:07  就只是小茗  阅读(2395)  评论(1编辑  收藏  举报