Skip to content

Instantly share code, notes, and snippets.

@justinobney
Created February 24, 2012 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinobney/1903821 to your computer and use it in GitHub Desktop.
Save justinobney/1903821 to your computer and use it in GitHub Desktop.
Simple Javascript & CSS Loader
var Loader = {};
(function (app) {
app.LinkCSS = function (href) {
//Link the stylesheet needed.
var headID = document.getElementsByTagName("head")[0];
var cssNode = document.createElement('link');
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.href = href;
cssNode.media = 'screen';
headID.appendChild(cssNode);
}
/** This loads a script asynchronously and then calls a callback function if supplied.
* Loader.getScript('stringURL',callback)
* Loader.getscript({js: 'stringURL', css: 'stringURL'},callback)
*/
app.getScript = function (url, success) {
var script = document.createElement('script');
script.src = url.js || url;
var head = document.getElementsByTagName('head')[0],
done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
done = true;
// callback function provided as param
if (typeof success === 'function') {
success();
}
script.onload = script.onreadystatechange = null;
head.removeChild(script);
};
};
head.appendChild(script);
if (url.css) {
app.LinkCSS(url.css);
}
}
})(Loader);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment