i have a script that has a function that should remove the old scripts and added other scripts, the thing is that if I removed the script and for some reason, one of the new scripts that should be added is the same as the old one that removed the browser gives me an error the variable name already exists. in other word, the removed script still lives in the browser, and its functions and variables are still in the memory and excutable. below are the two functions one for removing the old scripts and the other for adding new scripts.
function remove_js() {
var scripts = document.querySelectorAll("script[data-ams-reload='true']")
let urls = []
for (let i = 0; i < scripts.length; i++) {
scripts[i].remove()
let src = scripts[i].getAttribute('src')
urls.push(src)
}
return urls
}
function reload_js(scripts) {
var body = document.querySelector('body')
for (let i = 0; i < scripts.length; i++) {
var newscript = document.createElement('script');
newscript.src = scripts[i];
newscript.setAttribute('data-ams-reload', 'true')
body.appendChild(newscript);
}
}
does anyone know how to override this scenario?
When you load JavaScript into your page, it's not like CSS that's executed in "runtime". If you load JS, its loaded into the memory and then it will be always available.
A solution for your case can be achieved could be overriding the functions that you don't want to be executed from the JS you want to remove.
Something like this - original function:
function sayHello() {
console.log("Hello!"); //calling sayHello will print "Hello!"
}
Now, overriding it like this:
function sayHello() {
return false;
}
That way, calling sayHello will return false and do nothing.