插入的< script>是否可以标签可以多次运行而无需在JavaScript中使用eval? [英] Can an inserted <script> tag be run multiple times without using eval in JavaScript?

查看:57
本文介绍了插入的< script>是否可以标签可以多次运行而无需在JavaScript中使用eval?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用一个将js文件捆绑在html文件(小工具)中的插件。对于一个用例,我需要删除并重新实例化一个小工具以运行更新的代码。

I have to use a plugin which bundles js files inside html files (gadgets). For one use case I need to drop and re-instantiate a gadget to run updated code.

所以说我有 foo.html

<html>
  <head>
    <script src="foo.js"></script>
  </head>
  <body>...</body>
</html>

foo.js 被注入我实际文档的头部:

and foo.js which is the file being injected into my actual document's head:

alert("hello");

问题是我只能动态缓存HTML文件并将小工具声明为 foo.html?x = 123 ,但是我需要的JS文件仍然是 foo.js ,因此浏览器不会重新运行

Problem is I can only cachebust the html file dynamically and declare my gadget as foo.html?x=123, but the JS file I'm after will still be foo.js so the browser will not re-run it.

问题

< script> 标签已插入文档中并运行,是否有任何方法可以在不使用模块加载器或eval的情况下再次运行它?

Question:
Once a <script> tag is inserted into the document and run, is there any way to run it again without using a module-loader or eval?

谢谢!

推荐答案

您可以将代码包装在函数中的< script> 标记中,然后调用您的功能。这将允许您多次调用您的代码。像这样:

You could wrap your code in your <script> tags in a function then call your function. This will allow you to call your code to be called multiple times. Like this:

<script>
    function loaded(){
         // JavaScript here
    }
    loaded();
</script>
</body>

这篇关于插入的&lt; script&gt;是否可以标签可以多次运行而无需在JavaScript中使用eval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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