Created
October 4, 2012 15:55
-
-
Save gotomanners/3834564 to your computer and use it in GitHub Desktop.
Load a JS or CSS file dynamically
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
var loadResource = function (filename, filetype){ | |
var loadedResource = undefined; | |
if (filetype === "js"){ //if filename is a external JavaScript file | |
loadedResource=document.createElement('script'); | |
loadedResource.setAttribute("type","text/javascript"); | |
loadedResource.setAttribute("src", filename); | |
} | |
else if (filetype === "css"){ //if filename is an external CSS file | |
loadedResource=document.createElement("link"); | |
loadedResource.setAttribute("rel", "stylesheet"); | |
loadedResource.setAttribute("type", "text/css"); | |
loadedResource.setAttribute("href", filename); | |
} | |
if (typeof loadedResource !== undefined) { | |
document.getElementsByTagName("head")[0].appendChild(loadedResource) | |
} | |
}; | |
var unLoadResource = function (filename, filetype){ | |
var targetElement = (filetype === "js")? "script" : (filetype === "css")? "link" : "none"; | |
var targetAttr = (filetype === "js")? "src" : (filetype === "css")? "href" : "none"; | |
var allSuspects = document.getElementsByTagName(targetElement); | |
for (var i=allSuspects.length; i>=0; i--){ //search backwards for matching elements to remove | |
if (allSuspects[i] && allsuspects[i].getAttribute(targetAttr) !== null && allSuspects[i].getAttribute(targetAttr).indexOf(filename) !== -1) { | |
allSuspects[i].parentNode.removeChild(allSuspects[i]) //remove element by calling parentNode.removeChild(); | |
} | |
} | |
}; | |
// http://stackoverflow.com/questions/9425910/load-and-unload-javascript-at-runtime |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment