0

Depending on some conditions, different background images are loaded:

$('body').css('background','url(image.png)'); 

Is there a way to determine whether the background image has loaded? I need to execute a function when the image has been loaded.

7
  • You could possibly add an Image element with src="image.png" and attach an onLoad handler. The browser will only load the image once so if the Image element is created before the background-image property is set you should be able to use the onLoad handler. Untested, though :( Commented Aug 2, 2012 at 7:15
  • 1
    The already posted answers may work correctly for most cases, but beware that the images' load event has some caveats. Read this (scroll down to the Caveats of the load event when used with images part). Commented Aug 2, 2012 at 7:19
  • @FabrícioMatté the caveats are pretty disturbing. However I am using the native onload, i.e. img.onload = function(){} Is that safer to use than jQuery's .load()? Commented Aug 2, 2012 at 7:55
  • The onload HTML attribute is evaluated to a JS property, slightly different than jQuery .load() which attaches a load event handler. In the end of the day, both do pretty much the same, except that the jQuery devs (most often) try to solve compatibility issues better than just attaching a native event handler. Well, from experience, I've used the .load() handler for images a couple times and didn't see any issue, just leaving that reference so you will know about it in case an issue ever arises. =] Commented Aug 2, 2012 at 8:02
  • ^ And by both do pretty much the same I mean in functionality (both fire in the load event) but obviously an element can only have one onload attribute/load property while it allows having multiple .load() event handlers, but that's a slightly different topic. Commented Aug 2, 2012 at 8:08

2 Answers 2

2

You could load the image into a hidden <img> tag and assign an onload handler to the tag. In the onload handler you could populate the background image of the body (which should happen more or less instantly because the image is now in the browser cache) and then run your custom code as well.

var hiddenImg = new Image(); hiddenImg.onload = function(){ $('body').css('background','url(' + this.src + ')'); your_custom_onload_code(); }; hiddenImg.src = 'image.png'; 
Sign up to request clarification or add additional context in comments.

Comments

1
var img = new Image (); img.onload = function () { $('body').css('background','url(image.png)'); }; img.src = src; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.