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


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.)

var url=""
var extra="/74205

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

Thank you.


You can give your script tag an id:

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

and then set the src attribute to your desired value:

  var url="";
  var extra="/74205";
  document.getElementById('myScript').src = url+extra;

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