3636
3737 // loadCSS: load a CSS file asynchronously. Included from https://github.com/filamentgroup/loadCSS/
3838 function loadCSS ( href , before , media ) {
39+ // Arguments explained:
40+ // `href` is the URL for your CSS file.
41+ // `before` optionally defines the element we'll use as a reference for injecting our <link>
42+ // By default, `before` uses the first <script> element in the page.
43+ // However, since the order in which stylesheets are referenced matters, you might need a more specific location in your document.
44+ // If so, pass a different reference element to the `before` argument and it'll insert before that instead
45+ // note: `insertBefore` is used instead of `appendChild`, for safety re: http://www.paulirish.com/2011/surefire-dom-element-insertion/
3946 var ss = window . document . createElement ( "link" ) ;
4047 var ref = before || window . document . getElementsByTagName ( "script" ) [ 0 ] ;
48+ var sheets = window . document . styleSheets ;
4149 ss . rel = "stylesheet" ;
4250 ss . href = href ;
4351 // temporarily, set media to something non-matching to ensure it'll fetch without blocking render
4452 ss . media = "only x" ;
4553 // inject link
4654 ref . parentNode . insertBefore ( ss , ref ) ;
47- // set media back to `all` so that the styleshet applies once it loads
48- setTimeout ( function ( ) {
49- ss . media = media || "all" ;
50- } ) ;
55+ // This function sets the link's media back to `all` so that the stylesheet applies once it loads
56+ // It is designed to poll until document.styleSheets includes the new sheet.
57+ function toggleMedia ( ) {
58+ var defined ;
59+ for ( var i = 0 ; i < sheets . length ; i ++ ) {
60+ if ( sheets [ i ] . href && sheets [ i ] . href . indexOf ( href ) > - 1 ) {
61+ defined = true ;
62+ }
63+ }
64+ if ( defined ) {
65+ ss . media = media || "all" ;
66+ }
67+ else {
68+ setTimeout ( toggleMedia ) ;
69+ }
70+ }
71+
72+ toggleMedia ( ) ;
5173 return ss ;
5274 }
5375
152174 loadCSS ( fonts . content ) ;
153175 }
154176
155- } ( this ) ) ;
177+ } ( this ) ) ;
0 commit comments