动态加载JS和CSS

在项目中,除了通过压缩JS和CSS及开启web容器压缩功能可以提高性能外,还有一个更好的办法是动态加载CSS和JS

我们先来看一下下面的页面,这是一个列面页,新增是用一个DIV来实现的,这时要用到FCK,如果我们在加载列表时,就加载FCK,可是对列表的显示来说FCK不需要,而加载了FCK就会带来性能的损失,那我们就需要用动态加载来实现,如果用户不点击新增FCK是不被加载的

动态加载的实现

在一个公共JS中写下如下代码 有三个公共函数:getContextPath ,importJs和loadCSS

function getContextPath() {  //以js 方式用来获取上下文
    var b = document.location.pathname.substr(1);
    b = "/" + b.substr(0, b.indexOf("/"));
    return b;
}
var conextPath = getContextPath();

var impJsRec = new Object();//动态加载记录器,己加载的不再加载,要是没这个记录器,己加载的JS再加载时会和服务端多一次交互,虽然响应码是304 不传JS回来,让浏览器从缓存中加载
function importJs(url) {

    //对于URL的处理,你可以按你的方法处理,在MYPM中我们是有如下注释的约定
    if (url.indexOf("../") == 0) { //如果所传URL为../打头,去掉.. 直接和conextPath拼接
        url = conextPath + url.substring(2);
    } else {
        if (url.indexOf("/") != 0) { // 不以/打头,补上并和conextPath拼接
            url = "/" + conextPath + url;
        } else {
            if (url.indexOf(conextPath) != 0) { URL中不含conextPath
                url = conextPath + url;
            }
        }
    }
    if (typeof impJsRec[url] != "undefined") {//到记录器中查找,如不是未定义,就返回
        return;
    }

    
    var ajaxResut = dhtmlxAjax.getSync(url).xmlDoc.responseText;//AJAX 获取要加载的JS或CSS文本

    if (window.execScript) {
        try {
            window.execScript(ajaxResut);//执行动态加载
            impJsRec[url] = true;//记录到记录器中
        }
        catch (err) {
            return false;
        }
        return true;
    } else {
        eval.call(window, ajaxResut);//执行动态加载
        impJsRec[url] = true;//记录到记录器中
        return true;
    }
    return false;
}
var impCssRec = new Object();
function loadCSS(c) {
    if (c.indexOf("../") == 0) {
        c = conextPath + c.substring(2);
    } else {
        if (c.indexOf("/") != 0) {
            c = "/" + conextPath + c;
        } else {
            if (c.indexOf(conextPath) != 0) {
                c = conextPath + c;
            }
        }
    }
    if (typeof impCssRec[c] != "undefined") {
        return;
    }
    var d = document.createElement("link");
    d.rel = "stylesheet";
    d.rev = "stylesheet";
    d.type = "text/css";
    d.media = "screen";
    d.href = c;
    document.getElementsByTagName("head")[0].appendChild(d);
    impCssRec[c] = true;
}

按新增时,即弹出DIV界面后,调用如下

    var oEditor ;
    function loadFCK(){
        if(typeof oEditor != "undefined"){
            oEditor.SetData("");
            return;
        }
       importJs("/pmEditor/fckeditor.js");
        var pmEditor = new FCKeditor('reProStep') ;
        pmEditor.BasePath = conextPath+"/pmEditor/" ;
        pmEditor.Height = 200;
        pmEditor.ToolbarSet = "Basic" ;
        pmEditor.ToolbarStartExpanded=false;
        pmEditor.ReplaceTextarea();
    }
    function FCKeditor_OnComplete( editorInstance ){
        oEditor = FCKeditorAPI.GetInstance('reProStep') ;
        oEditor.SetData("");
        return;
    }  

原文地址:https://www.cnblogs.com/mypm/p/1958445.html