1 /*! loadCSS: load a CSS file asynchronously. [c]2016 @scottjehl, Filament Group, Inc. Licensed MIT */
5 var loadCSS = function( href, before, media ){
6 // Arguments explained:
7 // `href` [REQUIRED] is the URL for your CSS file.
8 // `before` [OPTIONAL] is the element the script should use as a reference for injecting our stylesheet <link> before
9 // By default, loadCSS attempts to inject the link after the last stylesheet or script in the DOM. However, you might desire a more specific location in your document.
10 // `media` [OPTIONAL] is the media type or query of the stylesheet. By default it will be 'all'
12 var ss = doc.createElement( "link" );
18 var refs = ( doc.body || doc.getElementsByTagName( "head" )[ 0 ] ).childNodes;
19 ref = refs[ refs.length - 1];
22 var sheets = doc.styleSheets;
23 ss.rel = "stylesheet";
25 // temporarily set media to something inapplicable to ensure it'll fetch without blocking render
28 // wait until body is defined before injecting link. This ensures a non-blocking load in IE11.
33 setTimeout(function(){
38 // Note: the ternary preserves the existing behavior of "before" argument, but we could choose to change the argument to "after" in a later release and standardize on ref.nextSibling for all refs
39 // Note: `insertBefore` is used instead of `appendChild`, for safety re: http://www.paulirish.com/2011/surefire-dom-element-insertion/
41 ref.parentNode.insertBefore( ss, ( before ? ref : ref.nextSibling ) );
43 // A method (exposed on return object for external use) that mimics onload by polling document.styleSheets until it includes the new sheet.
44 var onloadcssdefined = function( cb ){
45 var resolvedHref = ss.href;
46 var i = sheets.length;
48 if( sheets[ i ].href === resolvedHref ){
52 setTimeout(function() {
53 onloadcssdefined( cb );
58 if( ss.addEventListener ){
59 ss.removeEventListener( "load", loadCB );
61 ss.media = media || "all";
64 // once loaded, set link's media back to `all` so that the stylesheet applies once it loads
65 if( ss.addEventListener ){
66 ss.addEventListener( "load", loadCB);
68 ss.onloadcssdefined = onloadcssdefined;
69 onloadcssdefined( loadCB );
73 if( typeof exports !== "undefined" ){
74 exports.loadCSS = loadCSS;
79 }( typeof global !== "undefined" ? global : this ));