假设我有以下代码:
var img = document.createElement('img');
img.src = 'https://somePicture.png';
即使我不将图像附加到 DOM,图像是否会立即加载源数据?换句话说,我可以使用 img.onload()
进行回调,即使我不向用户显示图像也会运行吗?
最佳答案
是的,设置源属性将加载图像。
您可以将加载事件附加到图像,如果当前不在页面上,则设置源属性也是预加载图像时使用的最常用方法,以防止图像交换期间页面撕裂。
4.7.1 The img element
In a browsing context where scripting is disabled, user agents may obtain images immediately or on demand. In a browsing context where scripting is enabled, user agents must obtain images immediately.
A user agent that obtains images immediately must synchronously update the image data of an img element whenever that element is created with a src attribute. A user agent that obtains images immediately must also synchronously update the image data of an img element whenever that element has its src or crossorigin attribute set, changed, or removed.
https://www.w3.org/TR/html5/embedded-content-0.html#the-img-element
关于javascript - 设置图像的源是否也加载源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39111585/