How can I use a variable in a script tag source attribute?

Issue

is it possible to do something like this,
(really new to js, just wondering if something like this is possbile couldn’t find anything on the internet.)

<script>
var url="Pastebin.com"
var extra="/74205
</script>

<script src=url+extra></script>

Thank you.

Solution

You can give your script tag an id:

<script id="myScript"></script>

and then set the src attribute to your desired value:

<script>
  var url="Pastebin.com";
  var extra="/74205";
  document.getElementById('myScript').src = url+extra;
</script>

the script tag with id (myScript) should appear first in page in order for document.getElementById to work

Answered By – Shadi Shaaban

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published