Skip to content

Instantly share code, notes, and snippets.

@denysdovhan
Created July 1, 2014 20:10
Show Gist options
  • Save denysdovhan/6f3994f93be1960bef23 to your computer and use it in GitHub Desktop.
Save denysdovhan/6f3994f93be1960bef23 to your computer and use it in GitHub Desktop.
load a CSS file asynchronously.
/*!
loadCSS: load a CSS file asynchronously.
[c]2014 @scottjehl, Filament Group, Inc.
Licensed MIT
*/
function loadCSS( href, before, media ){
"use strict";
// Arguments explained:
// `href` is the URL for your CSS file.
// `before` optionally defines the element we'll use as a reference for injecting our <link>
// By default, `before` uses the first <script> element in the page.
// However, since the order in which stylesheets are referenced matters, you might need a more specific location in your document.
// If so, pass a different reference element to the `before` argument and it'll insert before that instead
// note: `insertBefore` is used instead of `appendChild`, for safety re: http://www.paulirish.com/2011/surefire-dom-element-insertion/
var ss = window.document.createElement( "link" );
var ref = before || window.document.getElementsByTagName( "script" )[ 0 ];
ss.rel = "stylesheet";
ss.href = href;
// temporarily, set media to something non-matching to ensure it'll fetch without blocking render
ss.media = "only x";
// inject link
ref.parentNode.insertBefore( ss, ref );
// set media back to `all` so that the styleshet applies once it loads
setTimeout( function(){
ss.media = media || "all";
} );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment