7

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.

1
  • 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. Commented Oct 23, 2016 at 1:23

5 Answers 5

18

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

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>

Comments

0

You can dynamic load js with your custom variables as below:

<html lang="en">

<body>
    <h1>Dynamic Script Loading Example</h1>

    <script>
        function loadScript(scriptUrl) {
            const script = document.createElement('script');
            script.src = scriptUrl;
            script.async = true;
            document.head.appendChild(script);
        }

        var variableUrl = 'https://example.com/path/to/your/script.js';
        loadScript(variableUrl);
    </script>
</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.