我使用 new Image()
创建一个新的图像元素。当我设置'src'属性时,会立即触发网络请求。为什么?有没有解释它的文件?
以下情况:
案例 1:
var img = new Image();
img.src = 'http://someurl.png';
案例 2:
var imgStr = '<img src="http://someurl.png">';
var div = document.createElement('div');
div.innerHTML = imgStr;
案例 3:
var script = document.createElement('script');
script.src = 'http://someurl.js';
// document.body.appendChild(script);
在case1和case2中,会立即触发网络请求。
在case3中,如果我不将脚本元素附加到正文中,则不会触发任何网络请求。
为什么?
最佳答案
我不确定这是否有帮助,preparing script 中的第 24 步, 解释了 script
标签的 src
行为,用户代理(浏览器)必须遵循:
For performance reasons, user agents may start fetching the classic script or module graph (as defined above) as soon as the src attribute is set, instead, in the hope that the element will be inserted into the document (and that the cross-origin attribute won't change the value in the meantime).
Either way, once the element is inserted into the document, the load must have started as described in this step. If the UA performs such prefetching, but the element is never inserted in the document or the src attribute is dynamically changed, or the crossorigin attribute is dynamically changed, then the user agent will not execute the script so obtained, and the fetching process will have been effectively wasted.
This解释了即使图像元素不在 DOM 中,也需要加载图像资源的方式和时间:
A user agent that obtains images immediately must synchronously update the image data of an img element, with the restart animation flag set if so stated, whenever that element is created or has experienced relevant mutations.
A user agent that obtains images on demand must update the image data of an img element whenever it needs the image data (i.e., on demand), but only if the img element's current request's state is unavailable. When an img element has experienced relevant mutations, if the user agent only obtains images on demand, the img element's current request's state must return to unavailable.
进一步了解 img
元素的 DOM manipulation :
The relevant mutations for an img element are as follows:
The element's src, srcset, width, or sizes attributes are set, changed, or removed.
The element's src attribute is set to the same value as the previous value. This must set the restart animation flag for the update the image data algorithm.
The element's
crossorigin
attribute's state is changed.The element is inserted into or removed from a picture parent element.
The element's parent is a picture element and a source element is inserted as a previous sibling.
The element's parent is a picture element and a source element that was a previous sibling is removed.
The element's parent is a picture element and a source element that is a previous sibling has its
srcset
, sizes, media, or type attributes set, changed, or removed.The element's adopting steps are run.
关于javascript - 为什么 "new Image()"会立即触发网络请求,而 "createElement('脚本')”却不会?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57087382/