Question

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.

Was it helpful?

Solution

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>

OTHER TIPS

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?

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();
  }
};

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top