0

This works:

<script src="chat/script.php?room=1&username=John&draggable=1"></script>

and this does not:

<script>
var username="John";
</script>  
<script src="chat/script.php?room=1&username="+username+"&draggable=1"></script>

Any idea how to fix that ?

6 Answers 6

8

Well, you can do that using client-side code, but not using HTML:

<script>
var username="John";
var script = document.createElement('script');
script.src = "chat/script.php?room=1&username="+username+"&draggable=1";
document.getElementsByTagName('script')[0].parentNode.appendChild(script);
</script>  
Sign up to request clarification or add additional context in comments.

Comments

3

Indeed, your variable username is a JavaScript variable. Outside the <script> tag, HTML doesn't know about it. You would need to insert the <script> tag from within JavaScript. this post describes how to do that.

In your case, it would be:

var my_script = document.createElement('script');
my_script.setAttribute('src','chat/script.php?room=1&username=' + username + '&draggable=1');
document.head.appendChild(my_script);

Comments

2

The content of the script tag is executed, nothing in its attributes will be executed. You can dynamically add a script tag like so:

var username="John";
var s = document.createElement('script');
s.src = "chat/script.php?room=1&username="+username+"&draggable=1";
documennt.getElementsByTagName("head")[0].appendChild(s);

This creates a new script element, sets the src property, and then inserts it into the HTML <head> tag.

Comments

1

Use a server-side language like PHP. That src attribute is not part of the Javascript. Only the code inside the script element.

Comments

0

Another method is to use document.write method as following:

var username = "John";
document.write( "<script src=\"chat/script.php?room=1&username=" + username 
                + "&draggable=1\"><" + "/script>" );

Note that i have break the </script> part such that it doesn't assumed as end closing tag of your main script block! the \"is used to escape the double quotation mark inside the string.

Comments

0

You can change any element's src using this in your JavaScript:

let myElement = (document.getElementById("myElementHTMLId").src =
"some string" + myVariable + "some string");

2 Comments

Another option is to use setAttribute Example: myElement.setAttribute('src', 'srcValue');
Not an answer, because they ask how to load a script with a dynamic url, not how to change url on an already loaded script

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.