且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript预加载图像:是否添加到DOM?

更新时间:2023-11-03 17:24:28

我测试过的所有浏览器 do 都加载图像,即使它们不在DOM中也是如此.您可以使用 https://jsfiddle.net/84tu2s9p/进行测试.

All browsers I've tested do load images even if they're not in the DOM. You can test this with https://jsfiddle.net/84tu2s9p/.

const img = new Image();
img.src = "https://picsum.photos/200/300";
img.onload = () => console.log("loaded");
img.onerror = err => console.error(err);

  • Safari 13、11.1、10.1
  • Edge 18
  • Firefox 72、70、62
  • Chrome 78、71
  • Opera 64
  • IE11
  • (并不是详尽的清单.我只是尝试了各种版本和浏览器.)

    (Not meant to be an exhaustive list. I just tried a variety of versions and browsers.)

    还有一个新的 image.decode() API,用于这种预加载图像的用例,并在实际解码图像以呈现图像时避免潜在的掉帧.Edge尚不支持它(尽管可以使用基于铬的Edge).

    There's also the new image.decode() API that is intended for this use case of preloading images and avoids potential dropped frames when actually decoding the image to render it. Edge doesn't support it yet (Chromium-based Edge will though).

    鉴于HTML Canvas可以使用图像而无需将它们放在DOM中,我认为它们已经可以加载图像.

    Given that HTML Canvas can use images without them being in the DOM, I think they have to load images.