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?

推荐答案

try this:

$('<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)');
});

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

EDIT: 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;

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})`;
});

Jquery相关问答推荐

如果文本框内容在 X 秒内没有更改,则进行 post 调用

使用带有 bootstrap 验证的 Ajax 函数时出现问题

ajax调用后Jquery事件不会触发

如何使用 JQuery Select 没有特定子元素的元素

Bootstrap 3 RC 1 中的 typeahead JavaScript 模块在哪里?

输入类型=文件的jQuery更改方法

组合数组时无法读取未定义的属性推送

在 contenteditable div 中的插入符号处插入 html

jQuery 对象和 DOM 元素

如何使用 jQuery 进行带命名空间的 XML 解析

jQuery .load() 调用不会在加载的 HTML 文件中执行 JavaScript

如何推迟内联 Javascript?

我想了解 jQuery 插件语法

更改占位符文本

判断文本框是否有空值

javascript过滤对象数组

父母的jQuery父母

javascript jquery单选按钮单击

如果一个元素正在被动画,我如何用 jQuery 找出?

在jQuery中,当它们都具有相同的名称时,如何获取单选按钮的值?