5

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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
  • 2
    The source cannot be variables by default as the source file is the script itself. I see you have very well explained options in answers below. – davewoodhall Oct 23 '16 at 01:23

4 Answers4

14

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

Shadi Shaaban
  • 1,670
  • 1
  • 10
  • 17
2

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.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
1

you will find the answer to your question in:

Add javascript variable to javascript src?

and

Use JS variable to set the src attribute for <script> tag

Community
  • 1
  • 1
phoenix
  • 351
  • 4
  • 11
1

yes it's possible

<script>
  var url="http://pastebin.com";
  var extra="/74205";

  var script = document.createElement("script");
  script.src = url + extra
  document.body.appendChild(script);
</script>