3 * Used to load CSS via JS so css doesn't block the browser.
6 /* @codingStandardsIgnoreFile */
9 loadCSS: load a CSS file asynchronously.
10 [c]2015 @scottjehl, Filament Group, Inc.
15 /* exported loadCSS */
16 w.loadCSS = function( href, before, media ){
17 // Arguments explained:
18 // `href` [REQUIRED] is the URL for your CSS file.
19 // `before` [OPTIONAL] is the element the script should use as a reference for injecting our stylesheet <link> before
20 // 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.
21 // `media` [OPTIONAL] is the media type or query of the stylesheet. By default it will be 'all'
23 var ss = doc.createElement( "link" );
29 var refs = ( doc.body || doc.getElementsByTagName( "head" )[ 0 ] ).childNodes;
30 ref = refs[ refs.length - 1];
33 var sheets = doc.styleSheets;
34 ss.rel = "stylesheet";
36 // temporarily set media to something inapplicable to ensure it'll fetch without blocking render
40 // 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
41 // Note: `insertBefore` is used instead of `appendChild`, for safety re: http://www.paulirish.com/2011/surefire-dom-element-insertion/
42 ref.parentNode.insertBefore( ss, ( before ? ref : ref.nextSibling ) );
43 // A method (exposed on return object for external use) that mimics onload by polling until 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 );
57 // once loaded, set link's media back to `all` so that the stylesheet applies once it loads
58 ss.onloadcssdefined = onloadcssdefined;
59 onloadcssdefined(function() {
60 ss.media = media || "all";