Javascript预加载图像:是否添加到DOM? [英] Javascript Preloading Images: Add to DOM, or not?

查看:39
本文介绍了Javascript预加载图像:是否添加到DOM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否需要在DOM中添加< img> 以便对其进行预加载?

Is it necessary to add an <img> to the DOM in order to preload it?

$(function whenDOMIsHappy(){

  var $img = $('<img />')
    .load(loadHandler)
    .error(errorHandler)
    .attr({src:"squatchordle-squashgarden.jpg"});

  $img.appendTo('body .preloads'); // is this at all necessary?

});
// assuming <div class="preloads" style="display:none;"></div> exists in <body>.

我已经看到了有关此技术的混合消息.我使用的是jQuery,但这个问题也适用于香草人.

I've seen mixed messages about this technique. I'm using jQuery, but the question applies to vanilla-people too.

我有兴趣在所有主流浏览器上保持正常运行.

I am interested in keeping this working in all major browsers.

推荐答案

我测试过的所有浏览器 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.

    这篇关于Javascript预加载图像:是否添加到DOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆