执行前删除<script>

时间:2018-10-15 21:18:07

标签: javascript html

我正在尝试使用普通javascript 从正文中删除其他      <身体>     ...          ...     

问题在于,当加载 部分中的脚本时,为时已晚( DOMContentLoaded ),并且 body 脚本已经存在在执行队列中。

在这种情况下,使用普通的javascript ,如何在执行之前从主体中删除 script 元素?

编辑:

仅说明一下, 不是我的。它是从其他地方提取的。

1 个答案:

答案 0 :(得分:0)

您无法在javascript中禁用其他脚本标签。尝试通过DOM操作删除脚本元素将不起作用。但是,在某些情况下,有一些技巧可以阻止脚本执行。

1。通过application/json作为内容类型

这将告诉浏览器将块解释为json。只有在html中存在content-type时,它才起作用,而从其他js代码中更改时,则不会。

<script type="application/json">console.log("Ignored")</script>

2。 CSP标头

您可以使用Content security policy标头仅允许脚本的某些来源。

<meta http-equiv="Content-Security-Policy" content="script-src 'self'">
<script>console.log("This will be executed")</script>
<script src="www.external-site.com/this-will-be-blocked.js"></script>