Skip to content

Instantly share code, notes, and snippets.

@jchysk
Created November 23, 2013 03:33
Show Gist options
  • Save jchysk/7610432 to your computer and use it in GitHub Desktop.
Save jchysk/7610432 to your computer and use it in GitHub Desktop.
Javascript CSS Loader
/**
* Framework independent function to load CSS
* @param path To the CSS file
* @returns {HTMLElement}
*/
function loadStyleSheet(path) {
var head = document.getElementsByTagName( 'head' )[0], // reference to document.head for appending/ removing link nodes
link = document.createElement( 'link' ); // create the link node
link.setAttribute( 'id', 'cssLKLoad'); // set ID to check if already loaded
link.setAttribute( 'href', path );
link.setAttribute( 'rel', 'stylesheet' );
link.setAttribute( 'type', 'text/css' );
var sheet, cssRules;
// get the correct properties to check for depending on the browser
if ( 'sheet' in link ) {
sheet = 'sheet'; cssRules = 'cssRules';
}
else {
sheet = 'styleSheet'; cssRules = 'rules';
}
head.appendChild( link ); // insert the link node into the DOM and start loading the style sheet
return link; // return the link node;
}
var $ = document;
var cssLoad = 'cssLKLoad';
if (!$.getElementById(cssLoad)) {
loadStyleSheet("style.css");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment