-
Image (pre)Loading with Javascript 02.02.09
Whilst working on a few digital projects recently, I’ve had occasions where using large (file size) images has been unavoidable. In some browsers, the image revealed slowly from top to bottom – and in others, the image loaded in low resolution first then ‘upgraded’. Neither worked for me, and having an image load by default wasn’t really a preferable or professional solution in my eyes.
So I’ve found a nice little Javascript workaround that I thought I’d share.
Using jQuery
The method is fairly simple to get your head around – you’re essentially creating a span or DIV, or whatever containing a spinning AJAX loading icon (here), then when your image has loaded in the background, jQuery hides your loading DIV and loads in your image in it’s place. Phew – easy as that huh? Check out the tutorial here.I had a few issues with that method – firstly, it was too long winded – and secondly, it only really worked when loading ONE image per page… but what about 5 or 6?
Then came the Prototype Library
Where I was able to create something a little easier, and a bit slicker using a little bit of my own Javascript (below). The method was to just wait until the page had fully loaded before I pulled in my image (targetted by ID). In the meantime, I put a little spinny icon in the background of my holding DIV. Easy.
<script type="text/javascript">
window.onload = begin;
function begin()
{
new Effect.Appear(document.getElementById('yourimage'), { duration: 1.0 });
}
</script>
Obviously you’re going to want Prototype and the effects library in your document first, then chuck this in, change ‘yourimage’ for the target ID (in this case, <img id=”yourimage” src=”whatever.jpg” />) and watch the magic! I guess the same would also work for jQuery – you’d need to have a play though.
wanna say something?