使用JS变量为< script>设置src属性.标签 [英] Use JS variable to set the src attribute for <script> tag

查看:95
本文介绍了使用JS变量为< script>设置src属性.标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将javascript变量用作同一jsp上另一个标签的'src'属性.

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. 将此代码放在第一个元素中.

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

  • 在第一个元素中使用文档写入方法.

  • Use document write method in the first element.

    document.write("<script type='text/javascript' src="+ google.com + "><\/script>");
    

  • 试图在第一个元素中设置一个JSTL变量并使用它.

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

    推荐答案

    尽管CDATA可以很好地工作,但使用document.createElement也是一个不错的选择.尤其是如果您打算向URL附加一些值,例如用于缓存清除.

    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>
    

    代码很好..:)

    这篇关于使用JS变量为&lt; script&gt;设置src属性.标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆