Created
December 11, 2014 16:52
-
-
Save phillipharding/e3e716d54a5e7f7b9512 to your computer and use it in GitHub Desktop.
Dynamically load a JS or CSS file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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