Can an inserted <script> tag be run multiple times without using eval in JavaScript?

左心房为你撑大大i 提交于 2020-01-06 02:32:10

问题


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.

So say I have foo.html:

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

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

alert("hello");

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.

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?

Thanks!


回答1:


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>


来源:https://stackoverflow.com/questions/28722476/can-an-inserted-script-tag-be-run-multiple-times-without-using-eval-in-javascr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!