javascript - 设置图像的源是否也加载源?

标签 javascript html

假设我有以下代码:

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/

相关文章:

html - Chrome 中伪元素的 CSS 过渡

javascript - Angularjs 将 json 响应合并为一个

javascript - AngularJs 上的数据刷新

javascript - ReactJS,在另一个模态之上显示模态

javascript - gpEasy CMS javascript 隐藏/显示文本

javascript - 如何用JS获取文档的绝对坐标?

javascript - EXT JS 商店的代理 : readers and writers

javascript - 无法启动SweetAlert2,抛出错误?

javascript - 在另一个函数的参数中捕获函数中的错误

javascript - 八进制数的按位运算