Dev
Dev

Reputation: 29

Removing a javascript from a html page dynamically

I have dynamically loaded a javascript by using :

  var fileref=document.createElement('script')

  fileref.setAttribute("type","text/javascript")

  fileref.setAttribute("src", "../scripts/sample.js");

  $("head").append(fileref);

Now to remove/unload the script the reverse doesr not work as a script once executed in a browser cannot be removed.

Is there a solution/workaround to this.?

Upvotes: 0

Views: 95

Answers (3)

A.J.
A.J.

Reputation: 9025

Easier to do it with jquery.js

1. Remove all Scripts

$('script').remove()

OR

2. Remove Specific Scripts

$('script').each(function(node){
   if (node.src == 'abc.js'){ # Check whether or not you want to remove it. 
       node.remove();
   }
}

Upvotes: 0

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18883

You can remove elements using removeChild:

var head = document.getElementsByTagName('head')[0];

//removing it from the head, where you added them
head.removeChild(script);

OR

As per your explanation in comments section try this solution :-

var fileref=document.createElement('script');

fileref.setAttribute("type","text/javascript");

fileref.setAttribute("src", "../scripts/sample.js");

fileref.setAttribute("id","scid");         //<-------add 'id' to script

$("head").append(fileref);

and then remove script with id as shown :

var element = document.getElementById("scid");
element.parentNode.removeChild(element);

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85653

You can remove the script like this:

$('script[src$="sample.js"]').remove();

Upvotes: 0

Related Questions