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);
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 :)
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);
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