Skip to content

Instantly share code, notes, and snippets.

@phillipharding
Created December 11, 2014 16:52
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 phillipharding/e3e716d54a5e7f7b9512 to your computer and use it in GitHub Desktop.
Save phillipharding/e3e716d54a5e7f7b9512 to your computer and use it in GitHub Desktop.
Dynamically load a JS or CSS file
function LoadResource(url, afterUi) {
var
p = new $.Deferred(),
resource = null,
headOrBody = document.getElementsByTagName(typeof afterUi !== 'undefined' && afterUi ? "body" : "head")[0];
if (url.match(/.js$/gi)) {
resource = document.createElement("script");
resource.type = "text/javascript";
if (resource.readyState) { // IE
resource.onreadystatechange = function() {
if (resource.readyState == "loaded" || resource.readyState == "complete") {
resource.onreadystatechange = null;
p.resolve(url);
}
};
} else { // good browsers
resource.onload = function() {
resource.onload = null;
p.resolve(url);
};
}
resource.src = url;
} else if (url.match(/.css$/gi)) {
resource = document.createElement('link');
resource.rel = 'stylesheet';
resource.type = "text/css";
resource.href = url;
p.resolve(url);
}
if (resource) {
headOrBody.appendChild(resource);
} else {
p.reject('unsupported resource type, only *.js or *.css are allowed!');
}
return p.promise();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment