Skip to content

Commit

Permalink
Small rewrite to help Javascript minification tools.
Browse files Browse the repository at this point in the history
  • Loading branch information
dlemstra committed Sep 23, 2015
1 parent 1985fd0 commit be76a71
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions loadCSS.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,23 @@ Licensed MIT
// `before` [OPTIONAL] is the element the script should use as a reference for injecting our stylesheet <link> before
// 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.
// `media` [OPTIONAL] is the media type or query of the stylesheet. By default it will be 'all'
var ss = w.document.createElement( "link" );
var doc = w.document;
var querySelectorAll = doc.querySelectorAll;
var ss = doc.createElement( "link" );
var ref;
if( before ){
ref = before;
}
else if( w.document.querySelectorAll ){
var refs = w.document.querySelectorAll( "style,link[rel=stylesheet],script" );
else if( querySelectorAll ){
var refs = querySelectorAll( "style,link[rel=stylesheet],script" );
// No need to check length. This script has a parent element, at least
ref = refs[ refs.length - 1];
}
else {
ref = w.document.getElementsByTagName( "script" )[ 0 ];
ref = doc.getElementsByTagName( "script" )[ 0 ];
}

var sheets = w.document.styleSheets;
var sheets = doc.styleSheets;
ss.rel = "stylesheet";
ss.href = href;
// temporarily set media to something inapplicable to ensure it'll fetch without blocking render
Expand All @@ -37,24 +39,26 @@ Licensed MIT
// Note: `insertBefore` is used instead of `appendChild`, for safety re: http://www.paulirish.com/2011/surefire-dom-element-insertion/
ref.parentNode.insertBefore( ss, ( before ? ref : ref.nextSibling ) );
// A method (exposed on return object for external use) that mimics onload by polling until document.styleSheets until it includes the new sheet.
ss.onloadcssdefined = function( cb ){
var onloadcssdefined = function( cb ){
var defined;
for( var i = 0; i < sheets.length; i++ ){
if( sheets[ i ].href && sheets[ i ].href === ss.href ){
var sheet = sheets[i];
if( sheet.href && sheet.href === ss.href ){
defined = true;
}
}
if( defined ){
cb();
} else {
setTimeout(function() {
ss.onloadcssdefined( cb );
onloadcssdefined( cb );
});
}
};

// once loaded, set link's media back to `all` so that the stylesheet applies once it loads
ss.onloadcssdefined(function() {
ss.onloadcssdefined=onloadcssdefined;
onloadcssdefined(function() {
ss.media = media || "all";
});
return ss;
Expand Down

0 comments on commit be76a71

Please sign in to comment.