I’ve an page that will load chunks of HTML using ajax. All those fragments will have images and some of them will be specified in a separate CSS using background-image. I wanted to write a pre-loader, so that the loaded chunk will show up only when all the loading is complete. If all the images would have been in the HTML chunk, I would load it, put it in a hidden element, then look for all the img tags and control if they are loaded (or put some callbacks in the load method). The problem is CSS I can’t do that so easily… So the only way that comes to my mind is to have a separate xml file with all the image locations and use it to create IMG elements, load them and when they are loaded display the chunk (so the images have already been pulled from the server). Do you know better approaches? Are there any ready components?
Share
If you accept a piece of advice, don’t do it this way. The priority here is the content, images are secondary. Don’t let the user wait for the content, because of the images. It will be a pain in the ass, especially on slow connections.
Your best bet it to use some placeholder/indicator images to give feedback about the loading components, and maybe to use some nice fade in effect for images in
<img>tags.Note: for small images you can try Data: URIs, which allow you to embed images into HTML or CSS files.
Never say no. 🙂 Here is a prototype of what you could use. It works fine for me in FF 3+, and IE 5.5+, but for some reason Chrome shows cssRules to be null. I have to figure out why. Another TODO is to merge
@import-ed rules in IE as it doesn’t serve then with the standard rule-set.Anyways, as you can see you need to pass it a
document, acallbackand there is an optionaltimeoutargument (10s by default).The
callbackwill be executed after every image is loaded in the document. (note if it fails with 404 the script will take care of it). Here you can do your fadeIn or show or somethin’.The
timeoutis there as a fallback, if anything would go wrong, it calls the callback anyway after a certain amount of time.