Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.


2 Answers

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

like image 162
Shadi Shaaban Avatar answered Jun 09 '26 16:06

Shadi Shaaban


The short answer is : NO

However, as you already have the required url to attach to the <script> tag's source attribute, this can be accomplished with the help of javascript itself.

First, we are going to create a script tag, and then modify its src attribute to point to the URL. Then, simply attach it to the required element with id, say, "foo"

<script>

  var url="Pastebin.com"
  var extra="/74205"
  var parent = document.getElementById("foo")
  var someScriptElement = document.createElement("script")
  someScriptElement.setAttribute("src",url+extra)
  foo.appendChild(someScriptElement)

</script>

That should do it.

like image 21
Sandesh Bhusal Avatar answered Jun 09 '26 15:06

Sandesh Bhusal