Skip to content

Instantly share code, notes, and snippets.

@adityapunjani
Last active August 29, 2017 12:16
Show Gist options
  • Save adityapunjani/516b90682f5b5d611c82 to your computer and use it in GitHub Desktop.
Save adityapunjani/516b90682f5b5d611c82 to your computer and use it in GitHub Desktop.
Simpler Async CSS load
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 <style> 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( "style" )[ 0 ];
ss.rel = "stylesheet";
ss.href = href;
// temporarily, set media to something non-matching to ensure it'll fetch without blocking render
ss.media = "tempMedia";
// inject link
ref.parentNode.insertBefore( ss, ref );
//reset media back to actual value
window.setTimeout(function(){ss.media = media || "all"}, 0)
return ss;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment