Home > front end >  How to dynamically add scripts to new webpages in javascript?
How to dynamically add scripts to new webpages in javascript?

Time:11-05

I'm currently learning javascript without any frameworks. How do you guys redirect to another html file, then assign a script to it dynamically?

So far, what I have done is:

onClick()
{
    window.location = newpage.html;
    var script = createElement('script');
     script.src = dynamic   'script.js';
    var body = document.findbyID('body');
     body.appendChild(src);
}

One of the examples of the dynamic script goes like this:

function addText()
{
    var text = createElement('p');
    text.innerhtml = sometext;
    var textHolder = findbyid('div_somewhere_in_html');
    body.appendChild(text);
}

The above code doesn't show the text inside the new webpage. The window.location command works. But after dynamically adding a text, it will not show up inside the new webpage. If I would console.log(window.location), it would only show my localhost:3000.

EDIT: All files are hosted locally.

CodePudding user response:

Since you own the target page, you can load (instead of pushing) a script based on a query string parameter. For example:

newpage.html

<!DOCTYPE html>
<html>
<body>
<script>
  const dynamic = new URL(location).searchParams.get('script-prefix');
  const script = document.createElement('script');
  script.src = dynamic   'script.js';
  document.body.appendChild(script);
</script>
</body>
</html>

anotherpage.html

When clicking the following link, newpage.html will load and execute a script called MyPrefixscript.js.

<html>
<body>
   <a href="/newpage.html?script-prefix=MyPrefix">My Link</a>
</body>
</html>

BTW, I used an anchor, but window.location = '/newpage.html?script-prefix=MyPrefix' would work as well.

  • Related