5

I have a couple of divs with background images. I would like to know how I can preload those background-images with a gif image since some of the background images are quite large. Doing the following does not work:

HTML:

<div id="glykopeels" onload="loadImage()">Glykopeels Content</div>
<div id="facials" onload="loadImage2()">Facials Content</div>

CSS:

#glykopeels{
        background: #ebebeb url(http://lamininbeauty.co.za/images/products/preloader.gif) no-repeat top right;
        background-size: contain;
    }
#facials{
    background: #ebebeb url(http://lamininbeauty.co.za/images/products/preloader.gif) no-repeat top right;
    background-size: contain;
    }

JS:

function loadImage(){
        document.getElementById('glykopeels').style.background = '#ebebeb url(http://lamininbeauty.co.za/images/products/glykopeel.jpg);';
    }
function loadImage2(){
        document.getElementById('facials').style.background = '#ebebeb url(http://lamininbeauty.co.za/images/products/facial.jpg);';
    }

I guess defining a different ID for that element in the onload function and defining css for that new ID is another possibility? Thus changing only the id of that element inside the onload function?

Thank you

DextrousDave
  • 6,603
  • 35
  • 91
  • 134

3 Answers3

5

First: there is no onload attribute for div's. EDIT: please read comments below, very interesting!

Secondly, you should place the url between quotes (escaping them if needed): url('http://lamininbeauty.co.za/images/products/facial.jpg')

Third, there was no image called preloader.gif, yet there was a image called loader.gif, so I used that one to 'fix' your css part for my solution in the jsfiddle demo link at the bottom.

During SO's server-move, I wrote a simple custom function for you that does exactly what you want.
Tested in IE6 and FF12.
To test this: please clear your browsers buffer, otherwise you can't SEE it in action (it would go too fast), since the images will probably be buffered on second view (again, perfect for your goal)!

JavaScript:

var repBg=function(a, t){ t=t||'*';  // by GitaarLAB
        var c=document.getElementsByTagName(t), i=c.length, r=[];
        while(i--){if (c[i].getAttribute(a)){r.push(c[i]);}} c=r; i=c.length;
        repBg.exec=function(){
            c[this['data-i']].style.background="#ebebeb url('"+this.src+"') no-repeat top right";
        };
        while(i--){ if (c[i].getAttribute(a)) {
            r=new Image();
            r.onload=repBg.exec;
            r['data-i']=i;
            r.src=c[i].getAttribute(a);
        }}  
};

// one could run repBg onload, but better to run it when the image has actually loaded, see html!
// window.onload=function(){  repBg('data-bg_img','div');  };

In your BODY: Add the attribute 'data-bg_img' (as per html5 convention, start with data-) to the elements you want to use this technique on and have it contain your background url, like this:

<div id="glykopeels" data-bg_img="http://lamininbeauty.co.za/images/products/glykopeel.jpg">Glykopeels Content</div>

The 'optional' initialization in your BODY:

<!--
trigger the replace background function when the loader image has actually loaded!
rewriting the onload with nothing to prevent infinite loop in IE6 (and greater?) !!
-->
<img src="http://lamininbeauty.co.za/images/products/loader.gif" style="display:none;" onload="this.onload=null; repBg('data-bg_img','div');">

Manual/explanation:
Images DO have a onload-event, so we place a loading-image in the html (at the bottom), that will trigger it's own onload-event, calling repBg() as soon as the browser has actually downloaded this loading-image!!!

The function repBg() takes up to 2 arguments:

  • the first mandatory string that contains the attribute that should be selected,
  • the second optional argument can define tagname (to limit the first argument).

When invoked, function repBg() will then search the body for elementTagNames that adhere to the second argument or * and then filter them with the first argument.
For each htmlObject that remains in the filtered htmlObjectCollection, a new image is created (not appended to the body) with the htmlObject's attribute-value (url) corresponding to the function's first argument as image-source, together with the htmlObjectCollection's referring id (attribute data-id) for reference.
As soon as these images load, they fire their onload event: calling repBg's exec method that replaces the background of the referenced htmlObject with the new freshly loaded (big) background-image (and the rest of your css). For further modularity you could expand on that function.

Lastly, note: the background images load in order they appear in source, aka the way you expect things to work!!

You can see it in action in this fiddle: http://jsfiddle.net/epdDa/


UPDATE VERSION 2: GRACEFUL FALLBACK!! AND COPY-PASTE NOBRAIN SOLUTION
It annoyed the living daylights out of me that my first solution did not provide graceful fallback. So I made a different solution that provides graceful fallback.
Also fully tested in IE6 and FF12 It works like this:
In your BODY: SIMPLY set your div's class to 'preload' and set it's style-attribute to the backgroundimage it should normally load. Like this:

<div id="facials" class="preload" style="background: #ebebeb url('http://lamininbeauty.co.za/images/products/facial.jpg') no-repeat top right;">Facials Content</div>

That was easy right?
Then place the following script in the HEAD (this is important) of the HTML:

// getElementsByClass original by dustin diaz, modified by GitaarLAB
document.getElementsByClassName=document.getElementsByClassName||function(searchClass,node,tag) {
    var classElements = [], i=0, j=0;
    if (!node){node = document;}
    if (!tag){tag = '*';}
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp('(^|\\\\s)'+searchClass+'(\\\\s|$)');
    for (; i < elsLen; i++) {
        if ( pattern.test(els[i].className) ) {
            classElements[j] = els[i]; j++;}
    } return classElements;
};

var repBg=(function(n,u,p,a,i,r){ // by GitaarLAB
    window.onload=function(){repBg(1);};
    i=new Image(); i.onload=function(){this.onload=null; repBg(2);};
    document.write("<style>."+n+"{background:"+p+" url("+u+") "+a+
        " !important; background-size: contain !important;}"+
        "</style>");
    i.src=u; r=0;
    return function(t){
        r=r+t; if(r>2){
            var c=document.getElementsByClassName(n), i=0, l=c.length, s;
            repBg.exec=function(){
                document.getElementById(this['data-id']).className='';
            };
            for(;i<l;i++){
                r=new Image();
                r.onload=repBg.exec;
                r['data-id']=c[i].getAttribute('id');
                s=c[i].getAttribute('style');
                try { // sane browsers
                    r.src=s.match(/url\('?([^'"]*)'?\)/i)[1];
                } catch(e) { // <IE8
                    r.src=s.cssText.match(/url\('?([^'"]*)'?\)/i)[1];
                }
            }
        }
    };
})('preload','http://lamininbeauty.co.za/images/products/loader.gif','#ebebeb','no-repeat top right');

Explanation:
It took me all night.. but I found a way.
If javascript is enabled, function repBg will start by writing an extra style-block to the documents head (where it is located, note to place it after your last css script), that sets the loader-background-image for all elements with the class 'preload' (thus displaying the load-image at pageload).
If a load-test image for the loading-image is loaded AND the window is loaded (to get to all the elements in the body), then it does basically the same as version 1. Only this time we fetch and match the url from the element's style-atribute and onload subsequently empty the element's style-attribute.

Since this function auto-executes and overwrites itself with a version similar to version 1 (as above), you can simply adjust parameters at the last line of function 'repBg'.
Note that: in it's initial sate repBg accepts a maximum of 4 arguments: className, Url, cssPrepend and cssAppend.

To see it in action (don't forget to clean your browsers buffer as explained),
click this fiddle: http://jsfiddle.net/epdDa/1/

Whoever uses this function, I would greatly appreciate it if you credit me!


UPDATE:
Extra explanations and answers to comments.

Main differences between the 2 versions
Technically both versions use almost the same techniques so there is no real difference there.

  • With version 1 the javascript is the glue that IS NEEDED to make the page work, but works in valid true xhtml and plain html.
    However, people with javascript turned off will get a nonfunctional site (with only loading-gifs displayed). Note that all other current answers, including the direction you where going, suffer from this problem!
  • With version 2 the javascript is only the spice that enhances the page-interaction (the way websites should be coded), but only works in html (or invalid xhtml).
    However this should make sure that people with javascript turned off still see a normal functioning page. IE: javascript is NOT NEEDED to display the site correctly. This concept is called 'graceful fallback' or 'degrading gracefully'. My vote no 1 for version 2.
    Extra bonus: this path gives you plain vanilla validating and SEMANTIC html since you use ancient trusty in-line style, id and class. My vote no 2 for version 2

Why did I choose to use in-line css? Why 'must' you use in-line css for this to work?
First of all, I spent hours to avoid in-line css. (I did not loose them, I learned way's that did not work, just as useful). Next, I want to point out that again all current answers including the direction you were going, had the actual background image url separated from the css, while in the css you were setting the loader image on each div separately, something where a class would have made more sense. Version 2 simply uses a configurable classname.

Both reading and writing css blocks in the document's HEAD is kind of a mess..
And did I mention linked external css files..??

In my opinion, all this would need so much extra code and cpu-cycles AND blocking/halting the browser on every pageload, in order for the core-priciple to work: the last valid css-rule applies. So the loading image is displayed as soon as possible since it is the specified background image at pageload, exactly what one would want from such a feature. And if the element is no longer part of the 'preload' class? Right: it's inline css takes effect, updated as fast as the browsr can render (if the image is already loaded). Nice.

So if you sacrifice (true) xhtml-support by simply using document.write, it currently still turns out this way is the 'best' way to go (as you can read in the previous 2 links). AND it would still work with an external linked css. My third (KISS-)vote for version 2.

My fourth vote for version 2 is because: the repBg function is prepared to have it's exec method(=function) 'upgraded' so you can only take out the 'preload' value from the class' valuelist. A simple replace() would suffice (currently left out for speed).

My fifth and final vote for version 2 is that because of it's graceful fallback setup, it is also relatively easy to fix for or block some browsers to use the extra 'spice'.

Finally, as for speed: I think version 2 will always feel snappier: onload-image is displayed almost as fast as the browser can fetch it (as if this extra css was always there to begin with), the loading-animations load snappy since: their load is already initiated in the head, and the browser will not download the overruled images until called for by the function. Plus they look interactive without distraction. But.. when the actual background images are loaded and the css updates: bam! the image is there, without the top-to-bottom-scanning'-effect'. That effect feels damn snappy to. Actually I'm convinced and will be doing an adaptation for images in the galary, for the snap-feel and increased perceived initial pageload.. Note, this is my opinion. Your mileage may vary haha.

Good luck!! (and please vote if you like/use this idea/function, thank you!!)

Community
  • 1
  • 1
GitaarLAB
  • 14,536
  • 11
  • 60
  • 80
  • All HTML elements, including `div`s, [have an `onload` attribute and `load` event](http://www.w3.org/TR/html5/webappapis.html#handler-onload). – icktoofay Aug 11 '12 at 22:39
  • @icktoofay: well.. [http://jsfiddle.net/hrUcX/](http://jsfiddle.net/hrUcX/) does not work for me (and apparently others).. so could you show us how to do it? Please teach us what we are missing!!! Since.. according to this [SO question](http://stackoverflow.com/questions/5026693/html-div-on-load-event) setting a div's (on)load would require hacks. – GitaarLAB Aug 11 '12 at 22:46
  • @icktoofay: [http://www.w3.org/TR/1999/REC-html401-19991224/struct/global.html#edef-DIV](http://www.w3.org/TR/1999/REC-html401-19991224/struct/global.html#edef-DIV), I can not find a onload specified. I tested your jsfiddle, and I have seen it work, but if I remove the image inside it.. It stops working: see [http://jsfiddle.net/QMbHs/1/](http://jsfiddle.net/QMbHs/1/). So why does it work? eventbubbling? – GitaarLAB Aug 11 '12 at 22:56
  • It listens for the `load` event on the `div`. `div`s do not fire `load` events themselves, but their child elements may. `img` elements fire `load` events, for example. The `img` fired a `load` event and it was propagated up to the `div`, which caught it. – icktoofay Aug 11 '12 at 22:58
  • I should note that you were referencing HTML 4 and I was referencing HTML 5. Apparently the `onload` attribute was added to `div`s in HTML 5, although I believe you could listen for the `load` event through `addEventListener` in HTML 4. – icktoofay Aug 11 '12 at 23:02
  • @icktoofay: Ok, thank you for the lesson! (I still find it a hack tough). Would this also work with the traditional event model (aka crossbrowser) instead of `addEventListener`? – GitaarLAB Aug 11 '12 at 23:02
  • @icktoofay: Then I still truly thank you for the lesson (and the image link in your fiddle :) ). Then for NOW I would not recommend this way (requiring more code for the new eventmodel to get this to work crossbrowser), this still is great info for FUTURE readers! – GitaarLAB Aug 11 '12 at 23:05
  • @icktoofay, the fact that some elements can catch `onload` if it is bubbled up for other elements does not mean that those elements supports `onload`. The `onload` in this case is supported by `img` and that tag fire the event, the others just take it and bubble it up, which is no the same thing. – Marcelo De Zen Aug 12 '12 at 09:24
  • @GitaarLAB: thank you VERY much for your effort and dedication, I will try to make your code work in my web page and I will send you a link when it works...thank you so much guys(@icktoofay and devendef as well)), some healthy discussion here. Ok, so the verdict here: HTML 5 support onload for div...right, but for all else, it is safest to assume that load event only supports , and – DextrousDave Aug 12 '12 at 12:22
  • Holy crap, I got it to work on the first try! Great code. One problem though, I don't like using inline styles(unless I have to). When I move the styling for the "facials" div to a stylesheet using #facials{styling...}, the whole function does not work anymore and the real image never shows up, it keeps displaying the gif animation...Also, won't loading all that code make the page load longer overall, hence defeating the whole purpose of preloading, and might as well leave the background images to load normally in the document without any preloading and gifs? – DextrousDave Aug 12 '12 at 12:36
  • Another thing...What do you mean by Gracefull fallback...your 1st function/solution works just as well...which one would you recommend using, keeping in mind the whole purpose of this exercise...? – DextrousDave Aug 12 '12 at 12:36
  • Hehe, true indeed! But it turned me into a believer and it was great fun to crack. For me, I'm done, one can easily expand/adjust on this modular function :) – GitaarLAB Aug 12 '12 at 20:17
  • @GitaarLAB...Thank you so much, you treated this with real motivation...And I will definitely use your answer, not because you did a lot of effort, but because I could get yours to work and it works pretty darn good!. Excellent answer,thank you. Also, to summarize your explanation for using inline styles, is because writing css styles to the external stylesheets with the load function takes up more time and resources right? – DextrousDave Aug 13 '12 at 09:45
  • @GitaarLAB...Also, preloading(so that they load in the background while the gifs are entertaining the user) actual images require that those images be loaded either in the head or body with javascript or normal html(as you are doing with the inline styles), so referencing them from an external source would be useless right? Anyways, my gut tells me that using the inline styles makes sense...I'm saying gut because my gut feeling is rather more developed than my HTML and Javascript skills :) – DextrousDave Aug 13 '12 at 09:47
  • There is however one more problem, but it has got nothing to do with your answer...The "background-size: contain" property is not supported in IE8 and lower, How do I fix that? also see this post: http://stackoverflow.com/questions/11924662/css-background-size-contain-property-for-ie8-and-lower – DextrousDave Aug 13 '12 at 10:47
  • @GitaarLAB: I just checked in IE now, and the actual images(as defined inline) never loads. But only in IE...why could that be? see my webpage: http://lamininbeauty.co.za/products.html. You said you tested it in IE6? I used IE9...but results should be the same – DextrousDave Aug 13 '12 at 11:50
  • First: damn that looks nice in action on your site!! The 'background-size:contain' is for the moment less important. Now for the strange part: please check the original fiddle in IE via this [link](http://fiddle.jshell.net/epdDa/1/show/) (and report back here). There it works (on my pc on IE6). Yet [via this link](http://jsfiddle.net/epdDa/1/) and your site, it only loads the LAST image. That is kind of strange/unpredictable. I'm looking into this right now. – GitaarLAB Aug 13 '12 at 18:15
  • Thanks GitaarLAB... but what is even more strange is that I'm testing in IE in browser and document mode for IE6-8, and it is only in IE 9 browser and document mode that this issue exists... – DextrousDave Aug 13 '12 at 18:34
  • yup, this 'link': http://jsfiddle.net/epdDa/1/show/ does exactly the same in IE9, it only shows the loader gif and never loads the actual background image. Also, on my site in IE, there is is a strange vertical grey line to the right of the product elements between rounded blocks and the start of the white background on the right... – DextrousDave Aug 13 '12 at 18:38
  • Well so far I found a couple of things: you served as (I think) illegal Xhtml, while true xhtml would not support version 2, due to LACK of `document.write`. Just want it to be clear. Another problem that already exists in your current source is differences between codepages!! For instance, see the 'replacement' characters in your comment about pushing IE to 'Edge-mode'. The replacement characters are already stored in your source. Please read-up a little on codepages, specifically utf8 versus iso and windows!!! Just as a well meant hint! – GitaarLAB Aug 13 '12 at 18:52
  • I'm a bit lost now...why is my code illegal xhtml, also, are you saing that the characters used in my comment are wrongly used? Any push in a right direction perhaps...? What about the IE 9 issue, is this(what you said) what is causing it? – DextrousDave Aug 13 '12 at 19:20
  • Ok, got your code from 5 minutes ago (since you are working live on the same code) working in IE6: so it now loads all images instead of the last image. Inside function repBg there is one for-loop, you can't miss it. Replace `for(;i – GitaarLAB Aug 13 '12 at 19:25
  • About your question about (x)html: Please read [absolute best source on browsermode-switching I have EVER seen](http://hsivonen.iki.fi/doctype/). Also note that IE10 is planning to DROP CONDITIONAL COMMENTS (sadly). – GitaarLAB Aug 13 '12 at 19:34
  • In short: I see you have specified xhtml at the top of your source. Since the `repBg` wrote to the head, I believe the xhtml was served as txt! AKA illegal xhtml, aka 'tag soup'. Otherwise as clearly explained in my answer, repBg version 2 would not have written to the head and should have given an error. So please update function repBg, test again in IE9 after the above fix. – GitaarLAB Aug 13 '12 at 19:41
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/15290/discussion-between-gitaarlab-and-dextrousdave) – GitaarLAB Aug 13 '12 at 19:42
2

1) div elements doens't have a load event, this event is only for body, images and script tags. EDIT: Like pointed by @icktoofay, in the HTML spec the onload exists for all elements, however this is not supported by the major browsers (yet).

2) place this script tag at the end of your html page:

<script>
    function loadImages() {
        var glykopeels = document.getElementById('glykopeels');
        var facials = document.getElementById('facials');

         glykopeels.style.backgroundImage = 'url(http://lamininbeauty.co.za/images/products/glykopeel.jpg)';
         facials.style.backgroundImage = 'url(http://lamininbeauty.co.za/images/products/facial.jpg)';

3) You can set style.background like you did, but do not put the ; at the end of the string, otherwise it will not work.

fiddle: http://jsfiddle.net/pjyH9/

EDIT

Seems like the loader image does not show because once the browser receive the first bytes of the new image it removes the loader.gif from the background. Let's take another approach. Here is a function that will load the image to cache and then - when image is loaded - set the image to the background of the element with the specified id.

function loadImageToBackground(elementId, imageUri) {
    var img = new Image();
    img.onload = function() {
       document.getElementById(elementId).style.backgroundImage = "url('" + imageUri +   "')";
    };
    img.src = imageUri;   
}

The on the elements that you want the loader:

// past the element id and the image url to the function
loadImageToBackground('glykopeels', ​'http://image....');

I'm pretty sure that this will work. The function loadImageToBackground do the basic work, you can extend and add more functionalies if you want.

Here is fiddle with a working example: http://jsfiddle.net/pjyH9/19/ (It loads 2 images with 1.5mb each, so you can see the loader in action).

Marcelo De Zen
  • 9,439
  • 3
  • 37
  • 50
  • thank you, I tried using just style.background but it does not load the real images - see http://jsfiddle.net/pjyH9/5/ – DextrousDave Aug 11 '12 at 15:56
  • I'm sorry, you cannot set `background` like a said. I edited my answer. – Marcelo De Zen Aug 11 '12 at 20:42
  • Why can't you set the background property? Works fine in my answer. – GitaarLAB Aug 11 '12 at 22:16
  • All HTML elements, including `div`s, [have a `load` event](http://www.w3.org/TR/html5/webappapis.html#handler-onload). – icktoofay Aug 11 '12 at 22:40
  • @icktoofay, nop. Only window, body and frameset have onload. From the specification: The following are the event handlers (and their corresponding event handler event types) that must be supported by Window objects, as IDL attributes on the Window object, and with corresponding content attributes and IDL attributes exposed on the body and frameset elements... that makes sense since the onload is for the document, not for single tags, since tags outside a document does not make sense, strictly speaking. – Marcelo De Zen Aug 12 '12 at 00:02
  • @devundef: That label is for the table below it. Scroll up to see the description for the table containing the item I was referencing: "The following are the event handlers (and their corresponding event handler event types) that must be supported by all HTML elements other than `body`, as both content attributes and IDL attributes, and on `Document` objects, as IDL attributes:" – icktoofay Aug 12 '12 at 00:56
  • @icktoofay you're right, in the HTML5 spec the `onload` must be fired for all elements. Good to know, sadly no browser seems to have implemented it until now (I tested on chrome 21 and firefox 14). – Marcelo De Zen Aug 12 '12 at 09:12
  • @GitaarLAB, it works. It tested here and will not work (chrome 21) if you set the url(image) instead of url('image'). I edited my answer – Marcelo De Zen Aug 12 '12 at 09:21
  • @devundef: That gif image does exist, you made a typo: it is loader.gif, not preloader.gif...Also, which is better supported by browsers now: url(image) or url('image')? – DextrousDave Aug 12 '12 at 11:08
  • @devundef: I still cannot get it to work, the preloader image loader.gif does not load/show. I tested in on my page where there are many more elements to load and the loading time is long, so the gif does have time to display...but it doesn't – DextrousDave Aug 12 '12 at 11:19
  • @DextrousDave, I always used url(image) and I haven't problems until now. But the spec says to use url('image'), so better to follow the spec. – Marcelo De Zen Aug 12 '12 at 19:53
  • For your interest, in light of your last comments and update, you might want to read the update to my answer. Trust me, I have a vivid recollection of the paths I also followed last night :) – GitaarLAB Aug 12 '12 at 20:15
1

I think what you're trying to do is get the background image to switch out to the big JPG image after it's loaded. You should be able to adapt something like this to work for you:

<html>
  <head>
    <title>Image Load Test</title>
    <script type="text/javascript">
      function loadImage(preloader, imageDiv) {
        document.getElementById(imageDiv).style.background = '#ebebeb url('+preloader.src+') no-repeat top right';
        // I think resetting the background property also resets backgroundSize.
        // If you still want it 'contained' then you need to set the property again.
        document.getElementById(imageDiv).style.backgroundSize = 'contain';
      }
    </script>
    <style type="text/css">
      #testImage {
              background: #ebebeb url(small-image.gif) no-repeat top right;
              background-size: contain;
      }
      #preloads { display: none; }
    </style>
  </head>
  <body>
    <div id="testImage">Some Content</div>
    <div id="preloads">
      <img src="full-image.jpg" onload="loadImage(this, 'testImage')">
    </div>
  </body>
</html>

The main difference here is that I'm preloading the JPG image in an <img> that's hidden in a <div> with the display: none property to keep it hidden. I'm not sure exactly what the onLoad event does for divs, but I'm pretty sure it's not what you're wanting. Putting an onLoad event in an img element causes the event to fire once the image has fully loaded, which I believe is what you want.

EDIT: I added a line in the JavaScript to reset the background-size property. If that's not what you wanted then just ignore that part.

DaoWen
  • 32,589
  • 6
  • 74
  • 101
  • Hi. Thank you for your answer. But your code is a bit confusing to me: Firstly, where is "preloader" defined? Secondly, I understand that the reason for using the hidden div is just to load the large image faster than to wait for the whole DOM to be ready and then execute the loading of the large image? – DextrousDave Aug 11 '12 at 19:33
  • The variable `preloader` is defined in the argument list for function `loadImage()`. When this function is called, the variable `preloader` is set to the value of the first argument/parameter and is accessible from within the function only. – wecsam Aug 11 '12 at 20:40
  • However, what I don't understand is the purpose of calling `loadImage()` with no arguments in the `onload` event for `
    `.
    – wecsam Aug 11 '12 at 20:41
  • @wecsam: You're very right about the onload event in the `testImage` element! I copied and pasted the code from the original question and apparently forgot to delete that part while modifying it. Thanks for pointing that out—it's removed now! – DaoWen Aug 12 '12 at 03:19
  • @DextrousDave: As wecsam already explained, `preloader` is defined as an argument to the `loadImage` function: `function loadImage(preloader, imageDiv)`. Loading having an `onLoad` event on a per-image basis will update the images one-by-one as they load rather than waiting for all images to load and updating them all at once. – DaoWen Aug 12 '12 at 03:24
  • Could you maybe put your idea into a fiddle please? – DextrousDave Aug 12 '12 at 11:37
  • Also, I understand that by the time the onload function on the tag starts, document.getElementById(imageDiv).style.background will basically be substituted as the argument "preloader"? – DextrousDave Aug 12 '12 at 11:46
  • @DextrousDave When `loadImage(preloader, imageDiv)` is called in ``, the keyword `this` is passed in as the `preloader` argument. `this` is a special keyword that, in this case, represents the element that calls the event. The `loadImage` function then uses `preloader` as a reference to the `` in order to retrieve the URL of the picture and set is as the background picture of `
    `.
    – wecsam Aug 12 '12 at 15:37