Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to use javascript to modify a script element?

Is there a way to use javascript to modify a script element?

Like for example:

HTML:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<script id="something" src="/js/file.js"></script>

Javascript:

var something = document.getElementById("something");
something.src = "/js/anotherfile.js"

Is it possible? Because I have a bit of code that works like that and it sort of doesn’t work

To be specific, here’s the code:

<!DOCTYPE html>
<html>

<head>
  <title>MyohTheGod's Website</title>
  <link rel="icon" type="image/x-icon" href="/supercorn.gif" defer>
  </link>
  <link id="css" href="/css/dark.css" rel="stylesheet" type="text/css">
  </link>
  <script src="/js/particles.js" defer></script>
  <script src="/js/header.js"></script>
  <script src="/js/theme.js"></script>
  <script>window.alert("Welcome to the Home of MyohTheGod. You can play games, check out our web proxies, and more. Also, please do check out the About page. Press OK to continue...");</script>
</head>

<body>
  -snip-
</body>
<script id="foot" src="/js/footer.js"></script>

</html>
<script>
  -snip-
</script>
var css = document.getElementById("css");
var foot = document.getElementById("foot");

function toggleDLmode(m) {
  -snip-
  if (dlmodebool) {
    css.href = "/css/dark.css"
    foot.src="/js/dark-footer.js"
  } else {
    css.href = "/css/index.css"
    foot.src="/js/footer.js"
  }
}

-snip-

>Solution :

It is working, do you inspect it? It does changed, but maybe you’re thinking, "hm why this /js/anotherfile.js is not downloaded?". Well because of the script tag is already rendered and already downloaded, so you can’t do that. What you can do though add NEW script tag.

Maybe this will help How to dynamically change the script src?. This links would explain more why your code "does not work".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading