I am trying to remove a script tag from the DOM in UI5. Here is my code and lang is parameter to the function that can change.
var something= document.getElementById("id");
if (lang.toLowerCase().indexOf("en") === 0 && !something) {
var s = document.createElement("script");
s.setAttribute(...);
s.setAttribute(...);
document.body.appendChild(s);
s.setAttribute(...);
s.setAttribute(...);
}else if(lang.toLowerCase().indexOf("en") !== 0 && something){
something.remove();
}else{
document.body.appendChild(something);
}
When ever something.remove() happens the functionality of script tag still displays in the webpage. I also get error when the code does document.body.appendChild(something);
The expected result is the script tag will be removed from the dom when something exists and lang is changed and added back when something is changed back to en.
The expected result is the script tag will be removed from the dom when something exists and lang is changed and added back when something is changed back to en.
Your code may or may not be removing the script element. You wouldn't be able to tell because removing the script element has no effect on the code that the script element loaded into the JavaScript environment. You can't "unload" code that's been loaded.
The script element is just a box the code comes in. Once the box has delivered the code to the JavaScript engine, the engine runs it and keeps anything that it creates around (although objects that nothing references can be garbage collected at some stage). The box is no longer needed, and removing it makes no difference.
Here's a simpler example in the browser:
<input id="btn" type="button" value="Click Me">
<script id="the-script">
function clickHandler() {
console.log("clickhandler called");
const script = document.getElementById("the-script");
if (script) {
script.remove();
console.log("First click, removed `script` element");
}
}
document.getElementById("btn").addEventListener("click", clickHandler);
</script>
You can't remove the code that the script element loaded.
You can write the code so that you can disable whatever code the script element loads and re-enable it later, by using a flag or unregistering/re-registering event handlers, etc.