Search code examples
csspagespeed

Array of stylesheets to optimize CSS delivery


I'm currently using this code to optimize my css delivery, but this is for one stylesheet only. How can I edit this to accept an array of stylesheets?

This code has been taken from suggestions at Google PageSpeed Insights developers.google.com/speed/docs/insights/OptimizeCSSDelivery

Also, if there's a simpler code snippet to use which will still get the job done, I'm 100% open to that as well! I've found several different answers for CSS delivery optimization, but none I've found account for delivering more than one stylesheet.

//add Font Awesome
      var cb = function() {
        var l = document.createElement('link'); l.rel = 'stylesheet';
        l.href = '//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.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);

Solution

  • You can make an array and loop through it.

    var cb = function() {
      var sheets = [
        '//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css',
        '//maxcdn.bootstrapcdn.com/font-awesome2/4.3.0/css/font-awesome.min.css',
        '//maxcdn.bootstrapcdn.com/font-awesome3/4.3.0/css/font-awesome.min.css' ];
      
      var h = document.getElementsByTagName('head')[0]; 
    
      for (var i = 0; i < sheets.length; i++) {
        var l = document.createElement('link'); 
        l.rel = 'stylesheet';
        l.href = sheets[i];
        //h.parentNode.insertBefore(l, h); // This would insert them before the head.
        h.appendChild(l); // Insert them inside the head.
      }  
    };
    
    var raf = requestAnimationFrame || mozRequestAnimationFrame ||
    webkitRequestAnimationFrame || msRequestAnimationFrame;
    if (raf) raf(cb);
    else window.addEventListener('load', cb);