Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to use a javascript variable as a 'src' attribute for another tag on the same jsp.

<script> var link = mylink // the link is generated based on some code </script> 

I want to create this new element as shown below.

<script src="mylink"> </script> 

On searching various forums, I have tried using the following options but they don't seem to work. I want this thing to work on all major browsers.

  1. Put this code in the first element.

    var script   = document.createElement("script"); script.type  = "text/javascript"; script.src   = "path/to/somelink"; document.body.appendChild(script); 
  2. Use document write method in the first element.

    document.write("<script type='text/javascript' src="+ google.com + "><\/script>"); 
  3. Tried to set a JSTL Variable in the first element and use it.

    <c:set var="URL" value="mylink"/> 

None of these ways were successful. Any suggestions on what is going wrong?

like image 407
1985percy Avatar asked Jun 22 '12 04:06

1985percy


People also ask

How do I add a variable to a script tag?

You can dynamically add a script tag like so: var username="John"; var s = document. createElement('script'); s. src = "chat/script.

What is src in script tag?

The src attribute specifies the URL of an external script file. If you want to run the same JavaScript on several pages in a web site, you should create an external JavaScript file, instead of writing the same script over and over again.


2 Answers

Though CDATA works fine, using document.createElement is also a great choice.. Especially if you intend to append some value to a URL, say for cache busting..

<script type="text/javascript">      var JSLink = "/Folder/sub_folder/version.js?version=" + Math.random();     var JSElement = document.createElement('script');     JSElement.src = JSLink;     JSElement.onload = OnceLoaded;     document.getElementsByTagName('head')[0].appendChild(JSElement);      function OnceLoaded() {         // Once loaded.. load other JS or CSS or call objects of version.js     } </script> 

Code well.. :)

like image 199
Mahesh Avatar answered Oct 09 '22 05:10

Mahesh


I use something similar to choice two. There is a slight mistake in your code because "google.com" needs to be surrounded by quotes.

To improve compatibility, you might want to write it as:

document.write("<script type='text/javascript' src='"+ x + "'><\/scr" + "ipt>"); 

In this situation, x would be the file to be included. You can define it as:

var x = "http://google.com/script.js"; 

OR

var x = "path/to/script.js"; 
like image 38
Gavy Avatar answered Oct 09 '22 05:10

Gavy