I am trying to add and remove js file dynamically by using the technique of add and remove html elements :
function start(){
var scriptElement = document.createElement('script');
scriptElement.src = 'js/game_page.js';
scriptElement.id = "game1";
document.body.appendChild(scriptElement);
}
start();
function stop(){
var a = document.getElementById("game1");
a.parentNode.removeChild(a);
}
stop();
In this case,the js file which is appended in DOM is still working even after calling stop()
Also share if any other way so that I could do the following thing,
Expectation:
Algorithm :
add work1.js
onclick of button{
if(condition1)
{
remove work1.js //may contain same declarations,so removing is also important
add work2.js
}
else
{
if(work2.js present)
{
remove work2.js
add work1.js
}
}
}
2
Answers
JavaScript is loaded with the page, individual script files cannot be loaded/unloaded after the page has loaded.
If you are trying to make certain code run only when a button is pressed, perhaps you can contain it in a function, or the method of an object and run it from there:
It would be a lot easier to help you with your situation if you update your question to include what code would be running from these scripts. Are you trying to modify the dom, change the page?
The issue you’re facing is that the JavaScript file
game_page.js
is not being removed as expected. This is because you are calling thestop()
function immediately after calling thestart()
function. Since the browser loads and executes scripts asynchronously, thestop()
function may run before thegame_page.js
script is fully loaded and executed.To achieve your desired behavior, you should ensure that the removal of the script happens after the script has finished loading and executing. You can do this by listening to the
load
event of the dynamically added script. Here’s how you can modify your code:With this modification, the
stop()
function will be called after thegame_page.js
script has finished loading and executing.Regarding your expectation of dynamically swapping JavaScript files, you can use a similar approach. Here’s a simplified example:
This code listens for a button click event and dynamically loads and replaces JavaScript files based on a condition. The
loadScript
function removes the current script (if any) and adds the new script dynamically.