Techagesite
Techagesite

Reputation: 475

Lazy load css with js

If i use something like this to lazy load some of my css files, is it possible to add 2 css files into it or can it only load 1?

<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>

Upvotes: 1

Views: 6987

Answers (1)

Miguel
Miguel

Reputation: 20633

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/

Upvotes: 6

Related Questions