Thursday, May 12, 2011

Implementing a stand-in "loading" image in javascript

First of all Happy Bike to Work day (BTW DAY)!

This is something like my 12th BTW day and I love seeing the masses of bicyclists out on the road especially on this day.

Now on to the subject of this post...

This had me a bit flummoxed, until I nailed down the magic way to set this up. Basically what I wanted to be able to was insert a stock image in place of a slower loading image. This slower loading (well, technically stream) ends up taking seconds to bring up after the page has finished rendering.

What was happening without this was I was staring a big empty rectangle after loading of the page, and thought it would be much much nicer to put in a pretty, albeit temporary, image in place.

The solution involves setting two image tags in the same div section. One visible and one hidden. Something like this:

<div id='stream_temp' style='visibility:visible;'>
  <img height=450 width=600 src='img/camera.jpg' alt='videoFull' border='4' >

<div id='stream' style='visibility:hidden;display:none;'>
  <img onload='displayStream()' height=450 width=600 
    alt='videoFull' border='4' ></img>

Both images are loading when the page is rendering in the browser, but the first image "stream_temp" is visible to the user, while the second "stream" is hidden from the user. The second image is the slow loading image. Using "display:none" means that the second image doesn't take any space on the page and screw up the layout.

The "non-standard" part of this solution is that "onload()" event, this isn't supported the w3c specification, but appears to be in every browser now. This means that the second image will call the javascript function after it has completed its loading. This script then toggles the state of the images:

function displayStream()
    var temp = document.getElementById("stream_temp");
    var stream = document.getElementById("stream"); = 'hidden'; = 'visible'; = 'none'; = 'block';

And Bob's your uncle. It's as simple as that.

No comments:

Post a Comment