如何检查背景图像是否已加载? [英] How can I check if a background image is loaded?

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

问题描述

我想在 body 标签上设置背景图片,然后运行一些代码 - 像这样:

I want to set a background image on the body tag, then run some code - like this:

$('body').css('background-image','http://picture.de/image.png').load(function() {
    alert('Background image done loading');
    // This doesn't work
});

如何确保背景图片已完全加载?

How can I make sure the background image is fully loaded?

推荐答案

试试这个:

$('<img/>').attr('src', 'http://picture.de/image.png').on('load', function() {
   $(this).remove(); // prevent memory leaks as @benweet suggested
   $('body').css('background-image', 'url(http://picture.de/image.png)');
});

这将在内存中创建一个新图像并使用 load 事件来检测 src 何时加载.

this will create a new image in memory and use load event to detect when the src is loaded.

在 Vanilla JavaScript 中,它看起来像这样:

in Vanilla JavaScript it can look like this:

var src = 'http://picture.de/image.png';
var image = new Image();
image.addEventListener('load', function() {
   body.style.backgroundImage = 'url(' + src + ')';
});
image.src = src;

它可以抽象为返回一个promise的方便的函数:

it can be abstracted into handy function that return a promise:

function load(src) {
    return new Promise((resolve, reject) => {
        const image = new Image();
        image.addEventListener('load', resolve);
        image.addEventListener('error', reject);
        image.src = src;
    });
}

const image = 'http://placekitten.com/200/300';
load(image).then(() => {
   body.style.backgroundImage = `url(${image})`;
});

这篇关于如何检查背景图像是否已加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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