在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ 用 innerHTML 寫入 script 標(biāo)簽不觸發(fā)請求。

用 innerHTML 寫入 script 標(biāo)簽不觸發(fā)請求。

// 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" 會觸發(fā)請求。
為什么用 innerHTML 寫入 script 不觸發(fā)請求呢?

回答
編輯回答
近義詞

是不是因為body.innerHTML的話頁面只剩一個script標(biāo)簽了

2017年4月3日 11:07
編輯回答
茍活

答案來自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.

我個人認(rèn)為是DOM在解析的時候解析了各個script,把script的attribute設(shè)為了可執(zhí)行,但當(dāng)你用innerHTML插入的時候,并沒有解析,所以script的attr為不可執(zhí)行,所以也就不會有src的請求

2017年6月3日 04:36