Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove appended script javascript

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.

like image 416
Robin Carlo Catacutan Avatar asked Feb 22 '12 07:02

Robin Carlo Catacutan


People also ask

How do I remove a script tag dynamically?

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.

How do I remove a script?

To remove a script from an applicationClick the Resources folder, right-click the script, and then click Remove.

How do I remove a DOM script?

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.

How do I remove a script in HTML?

Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.


2 Answers

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.

like image 118
Pavel Podlipensky Avatar answered Sep 21 '22 07:09

Pavel Podlipensky


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;
}
like image 42
James Hill Avatar answered Sep 18 '22 07:09

James Hill