views:

153

answers:

4

Searching for a js script, which will show some message (something like "Loading, please wait") until the page loads all images.

Important - it mustn't use any js framework (jquery, mootools, etc), must be an ordinary js script.

Message must disappear when the page is loaded.

A: 

You should do async ajax requests for the images and add a call back when it's finished.
Here's some code to illustrate it:

var R = new XMLHttpRequest();
R.onreadystatechange = function() {
  if (R.readyState == 4) {
    // Do something with R.responseXML/Text ...
    stopWaiting();
  }
};
the_drow
He doesn't need ajax requests. Anyway, callback would show only that request is finished, but not that image is loaded. You need observe image onload event.
Pawka
@Pawka: Won't the request be finished when the image is loaded?
the_drow
+1  A: 

Yeah an old-school question! This goes back to those days when we used to preload images...

Anyway, here's some code. The magic is the "complete" property on the document.images collection (Image objects).

// setup a timer, adjust the 200 to some other milliseconds if desired
var _timer = setInterval("imgloaded()",200); 

function imgloaded() {
  // assume they're all loaded
  var loaded = true;

  // test all images for "complete" property
  for(var i = 0, len = document.images.length; i < len; i++) {
    if(!document.images[i].complete) { loaded = false; break; }
  }

  // if loaded is still true, change the HTML
  if(loaded) {
    document.getElementById("msg").innerHTML = "Done.";

    // clear the timer
    clearInterval(_timer);
  }
};

Of course, this assumes you have some DIV thrown in somewhere:

<div id="msg">Loading...</div>
Jeff Meatball Yang
what if i want to do this for all the elements on the page and not just images?
renegadeMind
After the onload event, all images are allready loaded.
Maciej Łebkowski
Ok - I've taken the startup out of the window.onload...
Jeff Meatball Yang
thanks Jeff, but intervals are not the best solution, I hope it must stand on something like "$(document).ready" on jQuery.
Mike
A: 

Theoretically you could have an onload event on every image object that runs a function that checks if all images is loaded. This way you don´t need a setTimeOut(). This would however fail if an image didn´t load so you would have to take onerror into account also.

anddoutoi
and I "need" $$$ >.<
anddoutoi
anddoutoi, go and work, if you need money. I'm asking for some solution, not for a "free work", it can be a link on some script/site or something else. You think that I must pay for your theory, which gives no help for solving this question?
Mike
+2  A: 

Just add a static <div> to the page, informing user that the page is loading. Then add window.onload handler and remove the div.

BTW, what’s the reason of this? Don’t users already have page load indicators in their browsers?

Maciej Łebkowski
thanks, but I don't know how to implement "window.onload".
Mike