1 回答

TA贡献1799条经验 获得超9个赞
为了在背景中加载图像并在完成其他元素(如文本)后显示它,您需要在 Image Object 中加载图像,如下所示:
var img = new Image();
img.addEventListener('load', function () {
// Here you can set the url that was loaded in the background here
// to an actual `<img>` element. Browser uses cache now to load the image quickly.
});
img.src = 'image url here';
一旦您设置了 src,图像就会被加载,但没有人可以看到它。这将强制浏览器在后台加载图像并缓存它。因此,现在当您将确切的 src 设置为 img 元素时,浏览器将使用缓存来显示图像,因此图像将快速加载您想要显示的任何内容。
UPDATE --------
您可以在 jquery 中以更好的方式做到这一点:假设您有一堆图像。然后不是设置他们src的data-src属性,然后在加载所有图像时使用这个功能做一些事情:这是 HTML:
<img class="my-images" data-src="<image url 1>" />
<img class="my-images" data-src="<image url 2>" />
<img class="my-images" data-src="<image url 3>" />
<img class="my-images" data-src="<image url 4>" />
这是JS:
$.fn.whenImagesLoaded = function (callback) {
let found = $(this);
let counter = found.length;
found.each(function (i, item) {
let elem = $(item);
let img = new Image();
img.addEventListener('load', function () {
elem.on('load', function () {
counter--;
if (counter === 0 && callback) callback();
});
elem.attr('src', img.src);
});
img.src = elem.attr('data-src');
});
}
所以现在你不应该在图像上设置 src 但你必须这样做:
$('.my-images').whenImagesLoaded(function () {
// Hide loading text here and show images!
});
添加回答
举报