JS/CSS module LazyLoad之二
上一篇完成的JS的按需加载,这篇添加个新方法css,完成对CSS文件的加载。接口与JS相同,示例如下view sourceprint?1 LazyLoad.css([a.css, b.css, c.css], function(){
2 console.log(css模块加载完毕);
3 });
Firebug中效果如下,
上一篇对JS的加载实现是通过script元素,css则是通过link元素。而link元素仅IE6/7/8/9和Opera中支持其onreadystatechange事件,Firefox/Safari/Chrome既不支持onreadystatechange,也不支持onload。这里取了一个巧使用setTimeout延迟加载。
完整源码
view sourceprint?01 LazyLoad = function(win){
02 var list1,
03 list2,
04 isIE = /*@cc_on!@*/!1,
05 doc = win.document,
06 head = doc.getElementsByTagName(head)[0];
07
08 function createEl(type, attrs){
09 var el = doc.createElement(type),
10 attr;
11 for(attr in attrs){
12 el.setAttribute(attr, attrs[attr]);
13 }
14 return el;
15 }
16 function jsDone(obj){
17 list1.shift();
18 if(!list1.length){
19 obj.fn.call(obj.scope);
20 }
21 }
22 function cssDone(obj){
23 list2.shift();
24 if(!list2.length){
25 obj.fn.call(obj.scope);
26 }
27 }
28 function js(urls, fn, scope){
29 var obj = {
30 scope : scope || win,
31 fn : fn
32 };
33 list1 = [].concat(urls);
34 for(var i=0,len=urls.length; i<len; i++){
35 var script = createEl(script, {src: urls[i]});
36 if(isIE){
37 script.onreadystatechange = function(){
38 var readyState = this.readyState;
39 if (readyState == loaded || readyState == complete){
40 this.onreadystatechange = null;
41 jsDone(obj);
42 }
43 }
44 }else{
45 script.onload = script.onerror = function(){
46 jsDone(obj);
47 }
48 }
49 head.appendChild(script);
50 }
51 }
52 function css(urls, fn, scope){
53 var obj = {
54 scope : scope || win,
55 fn : fn
56 };
57 list2 = [].concat(urls);
58 for(var i=0,len=urls.length; i<len; i++){
59 var link = createEl(link, {
60 href : urls[i],
61 rel : stylesheet,
62 type : text/css
63 });
64 if(isIE){
65 link.onreadystatechange = function(){
66 var readyState = this.readyState;
67 if (readyState == loaded || readyState == complete){
68 this.onreadystatechange = null;
69 cssDone(obj);
70 &
补充:web前端 , JavaScript ,