3

I want to remove a script element and replace it with a different one. Lets say that you

<html>
<head>
<script src="default.js">
</head>

What I want to do is remove default.js and replace it with new.js on the click of a button. I know you can create a script like this:

var new_scr=document.createElement('script'); 
new_scr.src="new.js"; 
document.getElementsByTagName('head')[0].appendChild(new_scr);
2
  • 2
    You can change the source of the script tag, or create a new script tag, but javascript that is already loaded won't magically dissapear. Commented Feb 3, 2013 at 21:36
  • You might be able to use to get what you want. stackoverflow.com/questions/6659351/… Commented Feb 3, 2013 at 21:37

3 Answers 3

3

just stumbled across this and thought I'd jot down a vanilla solution for all of those no longer using JQuery.

  const newScript = document.createElement('script')
  const oldScript = document.querySelector('script[src*="default"]')
  newScript.src = 'new.js'
  oldScript.parentNode.insertBefore(newScript, oldScript.nextSibling)
  oldScript.parentNode.removeChild(oldScript)

Like the other answers have outlined the only way to replace a script is to locate it, place a new one after it and then remove the original.

Enjoy :)

Sign up to request clarification or add additional context in comments.

Comments

1

you can set the id for script tag and change the content based on the id instead of replacing it with new one.

or following might be useful code block for you.

var $jsRef = $('<script type="text/javascript" >').appendTo(document.body);
$jsRef.attr("src","jsFileName.js");

// You can also add content like this
$jsRef.append(content);


// You can change the js file name or content the same way
$jsRef.attr("src","newJSFileName.js");

// Changing the content like this
$jsRef.empty();
$jsRef.append(content);

Comments

0

I don't think you can "replace" it. The code will be parsed on page load, before your javascript has a chance to replace it. Therefore, even if you load something else, that javascript will already be running, i.e. in memory. I may be offbase, but I don't think you can "replace" a script unless you actually overwrite the items it established.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.