用 innerHTML 写入 script 标签不触发请求。

// no request
document.body.innerHTML = `<script src="https://cdn.jsdelivr.net/npm/jquery"></script>`;

// requested
const scriptElement = document.createElement(`script`);
scriptElement.src = `https://cdn.jsdelivr.net/npm/jquery`;
document.body.appendChild(scriptElement);

innerHTML 写入 imglink rel="stylesheet" 会触发请求。
为什么用 innerHTML 写入 script 不触发请求呢?

阅读 3.4k
2 个回答

答案来自Stack Overflow

This one was trivial.

As stated in spec (8.4 Parsing HTML fragments and 8.2.3.5 Other parsing state flags,) quote:

when using innerHTML the browser will

1.Create a new Document node, and mark it as being an HTML document.

2.If there is a context element, and the Document of the context element is in quirks mode, then let the Document be in quirks mode. Otherwise, if there is a context element, and the Document of the context element is in limited-quirks mode, then let the Document be in limited-quirks mode. Otherwise, leave the Document in no-quirks mode.

3.Create a new HTML parser, and associate it with the just created Document node. ...

and when parsing a <script> inside

1.The scripting flag is set to "enabled" if scripting was enabled for the Document with which the parser is associated when the parser was created, and "disabled" otherwise.

2.The scripting flag can be enabled even when the parser was originally created for the HTML fragment parsing algorithm, even though script elements don't execute in that case.

So it won't be executed, as long as you inject it with innerHTML.

And using innerHTML will prevent the <script> element created from being executed permanently.

As stated in spec (4.3.1 The script element,) quote:

Changing the src, type, charset, async, and defer attributes dynamically has no direct effect; these attribute are only used at specific times described below.

Concluding the described below is that, it only parse the src attribute when injecting the <script> to the document (no matter which, including the temporary one created when using innerHTML.)

So, as long as you want to inject a script to the document and make it executed, you have to use script = document.createElement('script').

Set its attributes like src and type, possibly the contents inside (by using script.appendChild(document.createTextNode(content))), then append it to the document.body.

我个人认为是DOM在解析的时候解析了各个script,把script的attribute设为了可执行,但当你用innerHTML插入的时候,并没有解析,所以script的attr为不可执行,所以也就不会有src的请求

是不是因为body.innerHTML的话页面只剩一个script标签了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题