how can I remove my appended script because it causes some problems in my app.
This is my code to get my script
var nowDate = new Date().getTime();
var url = val.redirect_uri + "notify.js?nocache=" + nowDate + "&callback=dummy";
var script = document.createElement('script');
script.src = url;
document.body.appendChild(script);
Then I have an auto load function, that causes to create another element script.
I want to get rid of the previous element that was appended before another element is added.
Dynamically removing an external JavaScript or CSS file To remove an external JavaScript or CSS file from a page, the key is to hunt them down first by traversing the DOM, then call DOM's removeChild() method to do the hit job.
To remove a script from an applicationClick the Resources folder, right-click the script, and then click Remove.
We can remove a script from the DOM by scanning through all scripts on the page, getting the parent node of that script, and then finally removing the child of that parent node.
Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.
Basically you can remove script tag by using a function similar to this one:
function removeJS(filename){
var tags = document.getElementsByTagName('script');
for (var i = tags.length; i >= 0; i--){ //search backwards within nodelist for matching elements to remove
if (tags[i] && tags[i].getAttribute('src') != null && tags[i].getAttribute('src').indexOf(filename) != -1)
tags[i].parentNode.removeChild(tags[i]); //remove element by calling parentNode.removeChild()
}
}
Note, it use filename parameter to identify target script to remove. Also please note that target script could be already executed at the time you're trying to remove it.
I would simply check to see if you've already added the script. Adding it and then removing is adds unnecessary complexity. Something like this should work:
var scriptAdded = false;
if(scriptAdded == false) {
document.body.appendChild(script);
scriptAdded = true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With