Reputation: 199
I have these three script files
<script type="text/javascript" src="script/inbox.js"></script>
<script type="text/javascript" src="script/news.js"></script>
<script type="text/javascript" src="script/friend.js"></script>
I am loading these files dynamically when user clicks certain links.
for example when user clicks inbox inbox.js is loaded and in similar manner.
All these files inbox.js,news.js,friend.js all have code that handles scroll event. Now even when user has switched to news from inbox still the handler for scroll in news is also getting called. I need to ensure that the handler for only that tab is callled when user is at particular tab.
Some directions that can be proceeded in to solve the problem is -
Please help me, which of these would be better way.
Upvotes: 0
Views: 551
Reputation: 5463
There is no way to "dynamically unload" a script after it has been loaded. You can remove the DOM element (assign an ID to it and call removeChild
on it's parent node) but the executed code is still working, e.g. all created variables still exist and event handlers set up in the script will still work.
You will need to unbind all handlers from the script if you only have event handling in it. Otherwise, you could consider introducing some global flag which you check in your script code and only perform certain functionality when the flag is set.
Upvotes: 0
Reputation: 11264
function removejscssfile(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 within nodelist 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()
}
}
removejscssfile("inbox.js", "js") //remove all occurences of "somescript.js" on page
This function can be used to remove js or css any type of script from document dynamically..
Upvotes: 1