JS/CSS module LazyLoad之二
时间:2011-04-30 来源:snandy
上一篇完成的JS的按需加载,这篇添加个新方法css,完成对CSS文件的加载。接口与JS相同,示例如下
LazyLoad.css(['a.css', 'b.css', 'c.css'], function(){ console.log('css模块加载完毕'); });
上一篇对JS的加载实现是通过script元素,css则是通过link元素。而link元素仅IE6/7/8/9和Opera中支持其onreadystatechange事件,Firefox/Safari/Chrome既不支持onreadystatechange,也不支持onload。这里取了一个巧使用setTimeout延迟加载。
完整源码
LazyLoad = function(win){ var list1, list2, isIE = /*@cc_on!@*/!1, doc = win.document, head = doc.getElementsByTagName('head')[0]; function createEl(type, attrs){ var el = doc.createElement(type), attr; for(attr in attrs){ el.setAttribute(attr, attrs[attr]); } return el; } function jsDone(obj){ list1.shift(); if(!list1.length){ obj.fn.call(obj.scope); } } function cssDone(obj){ list2.shift(); if(!list2.length){ obj.fn.call(obj.scope); } } function js(urls, fn, scope){ var obj = { scope : scope || win, fn : fn }; list1 = [].concat(urls); for(var i=0,len=urls.length; i<len; i++){ var script = createEl('script', {src: urls[i]}); if(isIE){ script.onreadystatechange = function(){ var readyState = this.readyState; if (readyState == 'loaded' || readyState == 'complete'){ this.onreadystatechange = null; jsDone(obj); } } }else{ script.onload = script.onerror = function(){ jsDone(obj); } } head.appendChild(script); } } function css(urls, fn, scope){ var obj = { scope : scope || win, fn : fn }; list2 = [].concat(urls); for(var i=0,len=urls.length; i<len; i++){ var link = createEl('link', { href : urls[i], rel : 'stylesheet', type : 'text/css' }); if(isIE){ link.onreadystatechange = function(){ var readyState = this.readyState; if (readyState == 'loaded' || readyState == 'complete'){ this.onreadystatechange = null; cssDone(obj); } } }else{ setTimeout(function (){ cssDone(obj); },50*len); } head.appendChild(link); } } return { js : js, css : css }; }(this);
LazyLoad_0.2.js下载
相关阅读 更多 +