2015-05-09 145 views
0

如果我使用這樣的事情來延遲加載我的一些CSS文件,是否可以添加2個CSS文件或它只能加載1?懶惰加載CSS與js

<script> 
var cb = function() { 
      var l = document.createElement('link'); 
      l.rel = 'stylesheet'; 
      l.href = 'yourCSSfile.css'; 
      var h = document.getElementsByTagName('head')[0]; 
      h.parentNode.insertBefore(l, h); 
     }; 

var raf = requestAnimationFrame || mozRequestAnimationFrame || 
      webkitRequestAnimationFrame || msRequestAnimationFrame; 

if (raf) { 
    raf(cb) 
} else { 
    window.addEventListener('load', cb); 
} 
</script> 

回答

4
function loadCss(filename) { 
    var l = document.createElement('link'); 
    l.rel = 'stylesheet'; 
    l.href = filename 
    var h = document.getElementsByTagName('head')[0]; 
    h.parentNode.insertBefore(l, h); 
} 

function cb() { 
    loadCss('yourCSSfile.css'); 
    loadCss('yourCSSfile2.css'); 
} 

window.addEventListener('load', cb); 

http://jsfiddle.net/vs9wLjvp/

+0

謝謝你,你會怎麼用確切的代碼我張貼壽辦呢? – Techagesite