38

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?

2
  • 1
    There is a popular script loading utility called require.js. It optimizes script loading and dependencies by making synchronous calls asynchronous. This may be of interest. Commented Jun 22, 2012 at 6:31
  • If you got an answer, you should accept one of the solutions. :) or provide the answer you found useful. Commented Aug 16, 2017 at 20:42

5 Answers 5

22

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.. :)

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

3 Comments

how bout if I need to load multiple js files. is there a specific syntax, or do I have to loop this whole script ?? thanks !!
Loop the whole script.. Any code you write would basically do that. Sorry for late response.
I tried this, and it works, but not as expected. In my case the sourced script is just a long text variable, a list of photos, etc., but when called upon in a resident script that variable is empty... unless... I insert an 'alert" statement in there. It seems some event must be triggered before the variable gets the string. Any ideas? I posted the problem here (stackoverflow.com/questions/54583628/…) but all responses were about off-topic issues.
7

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";

2 Comments

i tried this way with the quotes, but it is not working, cant see the script being added in the source code. also, did not understand why you say we need to do it like "'><\/scr" + "ipt>" ? any significance why we are concatenating here?
Some browsers, particularly older versions of Internet Explorer, thinks that this is the end of the <script> tag and stop processing the remaining code as JavaScript.
4

Are you able to use jQuery? If so you could use getScript():

http://api.jquery.com/jQuery.getScript/

$.getScript(mylink, function() {
   // do something using the JS that was loaded.
});

Comments

2

Try:

(function(d){
     var file = 'yourJS.js';
     var ref = d.getElementsByTagName('script')[0];
     var js = d.createElement('script');
     js.src = file;
     ref.parentNode.insertBefore(js, ref);
}(document));

What this does:

  1. Find the first script element on your page
  2. Creates a new script element with your supplied source.
  3. Then inserts that new element before the first existing script element.

Comments

0
<xsl:variable name="Path" select="/root/folder/"></xsl:variable> <!-- Global path variable. -->
<xsl:variable name="myScriptPath" select="concat($Path, 'myScript.js')"></xsl:variable> <!-- Relative script path variable. -->
<script src="{$myScriptPath}"/> <!-- Attach script. -->

Comments

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.