使用JS变量为<script>标记设置src属性

198*_*rcy 32 javascript jsp jsp-tags

我想在同一个jsp上使用javascript变量作为另一个标记的'src'属性.

<script>
var link = mylink // the link is generated based on some code
</script>
Run Code Online (Sandbox Code Playgroud)

我想创建这个新元素,如下所示.

<script src="mylink">
</script>
Run Code Online (Sandbox Code Playgroud)

在搜索各种论坛时,我尝试使用以下选项,但它们似乎不起作用.我希望这个东西适用于所有主流浏览器.

  1. 将此代码放在第一个元素中.

    var script   = document.createElement("script");
    script.type  = "text/javascript";
    script.src   = "path/to/somelink";
    document.body.appendChild(script);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在第一个元素中使用document write方法.

    document.write("<script type='text/javascript' src="+ google.com + "><\/script>");
    
    Run Code Online (Sandbox Code Playgroud)
  3. 试图在第一个元素中设置JSTL变量并使用它.

    <c:set var="URL" value="mylink"/>
    
    Run Code Online (Sandbox Code Playgroud)

这些方法都没有成功.什么是错误的任何建议?

Mah*_*esh 18

虽然CDATA工作正常,但使用document.createElement也是一个很好的选择.特别是如果你打算在URL上添加一些值,比如缓存清除...

<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>
Run Code Online (Sandbox Code Playgroud)

代码很好.. :)


Gav*_*avy 5

我使用类似于选择二的东西.您的代码中存在轻微错误,因为"google.com"需要被引号括起来.

要提高兼容性,您可能希望将其编写为:

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

在这种情况下,x将包含文件.您可以将其定义为:

var x = "http://google.com/script.js";
Run Code Online (Sandbox Code Playgroud)

要么

var x = "path/to/script.js";
Run Code Online (Sandbox Code Playgroud)