Skip to content

Instantly share code, notes, and snippets.

@Ultrabenosaurus
Created November 28, 2014 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ultrabenosaurus/61a0a6febce15f861e29 to your computer and use it in GitHub Desktop.
Save Ultrabenosaurus/61a0a6febce15f861e29 to your computer and use it in GitHub Desktop.
Deferred CSS loader.

Deferred CSS Loader

Based on the example from Google's PageSpeed Insights recommendation on optimising CSS delivery. Modified to be more robust and work in older browsers.

Usage

  1. Include the code in at the bottom of your HTML like Google's example.
  2. Make a server-side list of CSS files to defer.
  3. Convert that list, if it isn't already, to be a series of styles.push( '/path/to/style.css' ); in a single string.
  4. Output that string in place of //DEFERRED_STYLES in your final HTML output.
var cb = function(){
var styles = [];
//DEFERRED_STYLES
for( var i = styles.length - 1; i >= 0; i-- )
{
l = document.createElement( 'link' );
l.rel = 'stylesheet';
l.href = styles[i];
h = document.getElementsByTagName( 'head' )[0];
h.insertBefore( l, h.childNodes[h.childNodes.length-1] );
};
};
var raf = ( "undefined" != typeof requestAnimationFrame ) ? requestAnimationFrame : false ||
( "undefined" != typeof mozRequestAnimationFrame ) ? mozRequestAnimationFrame : false ||
( "undefined" != typeof webkitRequestAnimationFrame ) ? webkitRequestAnimationFrame : false ||
( "undefined" != typeof msRequestAnimationFrame ) ? msRequestAnimationFrame : false;
if( raf )
{
raf( cb );
}
else
{
if( "undefined" != typeof window.addEventListener )
window.addEventListener( 'load', cb );
else if( "undefined" != typeof window.attachEvent )
window.attachEvent( 'onload', cb );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment