动态加载CSS,JS文件

 1 var Head = document.getElementsByTagName('head')[0],style = document.createElement('style');
 2 //文件全部加载完成显示DOM
 3 function linkScriptDOMLoaded(parm){
 4     style.innerHTML = 'body{display:none}';//动态加载文件造成样式表渲染变慢,为了防止DOM结构在样式表渲染完成前显示造成抖动,先隐藏body,样式表读完再显示
 5     Head.insertBefore(style,Head.firstChild)
 6     var linkScript, linckScriptCount = parm.length, currentIndex = 0;  
 7     for ( var i = 0 ; i < parm.length; i++ ){
 8         if(/\.css[^\.]*$/.test(parm[i])) {
 9             linkScript = document.createElement("link");
10             linkScript.type = "text/" + ("css");
11             linkScript.rel = "stylesheet";
12             linkScript.href = parm[i];
13         } else {
14             linkScript = document.createElement("script");
15             linkScript.type = "text/" + ("javascript");
16             linkScript.src = parm[i];
17         }
18         Head.insertBefore(linkScript, Head.lastChild)
19         linkScript.onload = linkScript.onerror = function(){
20             currentIndex++;
21             if(linckScriptCount == currentIndex){
22                 style.innerHTML = 'body{display:block}';
23                 Head.insertBefore(style,Head.lastChild)
24             }
25         }
26     }  
27 }
28 //异步加载css,js文件
29 function linkScript(parm, fn) {
30     var linkScript;
31     if(/\.css[^\.]*$/.test(parm)) {
32         linkScript = document.createElement("link");
33         linkScript.type = "text/" + ("css");
34         linkScript.rel = "stylesheet";
35         linkScript.href = parm;
36     } else {
37         linkScript = document.createElement("script");
38         linkScript.type = "text/" + ("javascript");
39         linkScript.src = parm;
40     }
41     Head.insertBefore(linkScript, Head.lastChild)
42     linkScript.onload = linkScript.onerror = function() {
43         if(fn) fn()
44     }
45 }
46  
47  
48  
49 linkScriptDOMLoaded([
50     "/content/bootstrap/assets/css/style.css",
51     "/content/bootstrap/assets/css/bootstrap.css",
52     "/content/bootstrap/assets/js/footable/css/footable.standalone.css"
53 ])
54 linkScript("/content/bootstrap/assets/css/entypo-icon.css")
55 linkScript("/content/bootstrap/assets/css/font-awesome.css")

 

posted @ 2018-08-31 14:43  yuwenjing  阅读(3774)  评论(0编辑  收藏  举报