views:

147

answers:

3

Scenario: Preloading images

  1. Perform an ajax query
  2. Show loading screen
  3. Retrieve results from ajax query
  4. Insert images into the dom
  5. Wait for images to finish loading
  6. Hide loading screen

I was thinking of doing the following:

function ajaxCallback(results) {
   /* snip insert into dom code */

   $(".waitForLoad").each(function() {
      imageLoadingCount++;
      $(this).load(imageLoaded);
   });
}

var imageLoadingCount = 0;
function imageLoaded() {
   imageLoadingCount--;
   if (imageLoadingCount == 0)
      HideLoadingScreen();
}

I'm not quite sure of the interaction between the browser DOM and javascript. Does the DOM wait for the javascript to finish executing before it starts loading the images? I'm worried about possible race conditions.

A: 

Javascript should run in parallel with the loading, unless you're using all the connections with AJAX requests. The browser still functions normally while javascript runs, which is the whole point behind it in the first place.

Ian Elliott
A: 

The load event observer is a little scary because it will work only if you set it before the element has completely loaded, if you set it after that nothing will happen. Therefore, it really depends on when you call ajaxCallback(). I would recommend using onSuccess rather than onComplete.

Also, I wonder if it's possible to use the load event observer on $(".waitForLoad") itself?

Detect
A: 

You can safely execute ajaxCallback within $.ready() and get rid of most problems. And note that DOM is not updated for newly created tags.

Also note that - The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel.

In many scenarios, users will get annoyed if you are showing them loading screens for more than a second or two. Waiting for images to get loaded is hardly a good idea.

Arpit Tambi