Skip to content

Instantly share code, notes, and snippets.

@adammcarth
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save adammcarth/6866bb4fad3b6021d4dc to your computer and use it in GitHub Desktop.

Select an option

Save adammcarth/6866bb4fad3b6021d4dc to your computer and use it in GitHub Desktop.
/*!
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/
// DELETE OLD STYLESHEET IF IT ALREADY EXISTS
var current_ss = window.document.getElementsByTagName( "link" );
// loop through each stylesheet in the DOM as `ss`
for ( var i = 0, ss; ss = current_ss[i]; i++ ) {
console.log(ss);
// <link rel="stylesheet" href="test.css" media="all">
console.log(ss.media);
// "only x"
if ( ss.href === href && ss.media === media ) {
ss.remove();
}
}
// ADD THE NEW STYLESHEET
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";
} );
}
loadCSS("test.css");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment