Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...