Check loading background image

This is my code:

$('<div>') .css('background-image', 'url(' + images[imageToLoad].url + ') no-repeat center center') .appendTo('#image-container') .hide() .load(function () { loadedImages.push($(this)); }); 

Somehow, the load event never fires here when the background image is loaded. What event should I capture to know when the background is loaded?

+4
source share
2 answers

What @variant said + code, since the img onload event does not always fire:

 var img = new Image(), div = $( "<div>" ).appendTo( "#image-container").hide(); img.onload = function(){ if( this.isLoaded ) { return; } this.isLoaded = true; loadedImages.push( div.css( "background-image", "url('"+this.src+"') no-repeat center center" ) ); } img.src = images[imageToLoad].url; if( ( img.complete || img.readyState === 4 ) && !img.isLoaded ) { img.onload(); } 
+3
source

There is no event.

What you can do is preload the image using the IMG tag and listen to the load event on it. When it's fired, add your div with the background image in the DOM. The image is already in the browser cache, and the download will be instant.

+1
source

All Articles