Categories
JavaScript Answers

How to force a script reload and re-execute with JavaScript?

Spread the love

Sometimes, we want to force a script reload and re-execute with JavaScript.

In this article, we’ll look at how to force a script reload and re-execute with JavaScript.

How to force a script reload and re-execute with JavaScript?

To force a script reload and re-execute with JavaScript, we can make a copy of the original script, remove it, and then append it again.

For instance, we write

const scriptTag = document.createElement("script");
scriptTag.innerText = "document.body.innerHTML += 'Here again ---<br>';";
const head = document.getElementsByTagName("head")[0];
head.appendChild(scriptTag);

setInterval(() => {
  head.removeChild(scriptTag);
  const newScriptTag = document.createElement("script");
  newScriptTag.innerText = scriptTag.innerText;
  head.appendChild(newScriptTag);
  scriptTag = newScriptTag;
}, 1000);

We create the scriptTag with createElement.

And then we set its innerText property to add the script we want to run inside.

Next, we get the head element with getElementsByTagName.

Then we call head.appendChild with scriptTag to append it to the head.

In the setInterval callback, we remove the original scriptTag with head.removeChild.

Then we we recreate the script tag as newScriptTag and append it again to the head with head.appendChild.

Conclusion

To force a script reload and re-execute with JavaScript, we can make a copy of the original script, remove it, and then append it again.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *