Yaffs site version 1.1
[yaffs-website] / web / modules / contrib / advagg / advagg_mod / js / loadCSS.js
1 /**
2  * @file
3  * Used to load CSS via JS so css doesn't block the browser.
4  */
5
6 /* @codingStandardsIgnoreFile */
7
8 /*!
9 loadCSS: load a CSS file asynchronously.
10 [c]2015 @scottjehl, Filament Group, Inc.
11 Licensed MIT
12 */
13 (function(w){
14   "use strict";
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'
22     var doc = w.document;
23     var ss = doc.createElement( "link" );
24     var ref;
25     if( before ){
26       ref = before;
27     }
28     else {
29       var refs = ( doc.body || doc.getElementsByTagName( "head" )[ 0 ] ).childNodes;
30       ref = refs[ refs.length - 1];
31     }
32
33     var sheets = doc.styleSheets;
34     ss.rel = "stylesheet";
35     ss.href = href;
36     // temporarily set media to something inapplicable to ensure it'll fetch without blocking render
37     ss.media = "only x";
38
39     // Inject link
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;
47       while( i-- ){
48         if( sheets[ i ].href === resolvedHref ){
49           return cb();
50         }
51       }
52       setTimeout(function() {
53         onloadcssdefined( cb );
54       });
55     };
56
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";
61     });
62     return ss;
63   };
64 }(this));