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.
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';
Imageelement withsrc="image.png"and attach anonLoadhandler. The browser will only load the image once so if theImageelement is created before thebackground-imageproperty is set you should be able to use theonLoadhandler. Untested, though :(loadevent has some caveats. Read this (scroll down to theCaveats of the load event when used with imagespart).img.onload = function(){}Is that safer to use than jQuery's.load()?onloadHTML attribute isevaluated to a JS property, slightly different than jQuery.load()which attaches aloadevent 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.=]both do pretty much the sameI mean in functionality (both fire in theloadevent) but obviously an element can only have oneonloadattribute/loadproperty while it allows having multiple.load()event handlers, but that's a slightly different topic.