« Previous

A Useful JavaScript Image Loader

Posted on February 21, 2008
Filed Under Javascript | 6 Comments
Tags: , , ,


imageloader.js
Online Example

I released a YUI implementation of image gallery script a month ago. While it was quite an enjoyable experience to explore the potential of YUI and JavaScript, I found I have created many userful code snips (for instance this Loading Panel) along the way.

Today I am going to show you another useful JavaScript code snip: Image Loader. What! You might ask. I admit that name is too generic, but it does what it does - it helps you to load images using JavaScript. Just give it an image URL, it will return a DOM image object that can be used for dynamic loading of images. This script provides a loading completion event, which is very useful for displaying preloader or extra information when the image is being loaded.

The original image loader I created relies on YUI, but I want to make it as portable as possible, so I created a standalone version.

Usage

First you need to create a new instance of ImageLoader, and feed the loader with an image URL:

var loader = new ImageLoader('IMAGE_URL');

Set event handler (which is a function) so that you can process the image after it is loaded:

loader.loadEvent = function(url, image){
   //actions to perform when the image is loaded
   //alert(url + ' is loaded');
   document.body.appendChild(image);
  //hide loading indicator if applicable
}

For example, if you were showing a loading image before the loading sequence and you want to hide it as soon as the image is loaded, you can put your code inside of loadEvent handler. The load Event handler takes two arguments, which are self-explanatory:

  • url - The url you specified when instantiating the loader
  • image - DOM reprentation of the image, you can call foo.appendChild(image)

Invoke load method on the loader to load the image:

loader.load();

That's all. Still confused by what can this image loader do? Try this example to find out.

As shown in the online example, combining with YUI loading panel, you can make an interesting image loading effect effortlessly.

Complete Source Code

imageloader.js

/**
* A simple JavaScript image loaderimage loader
* @author Cuong Tham
* @url http://thecodecentral.com/2008/02/21/a-useful-javascript-image-loader
* @usage
* var loader = new ImageLoader('IMAGE_URL');
* //set event handler
* loader.loadEvent = function(url, image){
*   //action to perform when the image is loaded
*   document.body.appendChild(image);
* }
* loader.load();
*/

//source: http://snipplr.com/view.php?codeview&id=561
// Cross-browser implementation of element.addEventListener()
function addListener(element, type, expression, bubbling)
{
  bubbling = bubbling || false;
  if(window.addEventListener)	{ // Standard
    element.addEventListener(type, expression, bubbling);
    return true;
  } else if(window.attachEvent) { // IE
    element.attachEvent('on' + type, expression);
    return true;
  } else return false;
}

var ImageLoader = function(url){
  this.url = url;
  this.image = null;
  this.loadEvent = null;
};

ImageLoader.prototype = {
  load:function(){
    this.image = document.createElement('img');
    var url = this.url;
    var image = this.image;
    var loadEvent = this.loadEvent;
    addListener(this.image, 'load', function(e){
      if(loadEvent != null){
        loadEvent(url, image);
      }
    }, false);
    this.image.src = this.url;
  },
  getImage:function(){
    return this.image;
  }
};

Go to Top

More interesting posts ...

Comments
6 Comments so far
  1. Vayu February 22, 2008 7:33 am

    Hi. I cant seem to get it to upload images from local computer. How do I do this?

  2. Cuong February 22, 2008 10:00 pm

    You can't. This is not a image upload script but rather a script that dynamically loads image for a given URL.

  3. Ganesh March 6, 2008 2:18 am

    Interesting article. I am basically a jquery user and have been using an image preloader plugin for jquery for this purpose. You can see it at http://www.mattfarina.com/2007/02/01/preloading_images_with_jquery.
    Still, your article is more useful because, that plugin doesn't have support for loadEvent.

  4. JacobF April 15, 2008 6:29 am

    Great :)
    I'm using it for a map that can be repositioned. It got rid of the map (the map is a div with a background image) disappearing and then showing up when it's loaded. Nice :D

  5. ade June 19, 2008 8:39 am

    This is great:)

    However, is it possible to tie this into a file upload? So a user can uplaod a file from their pc to a server and then it appears in the page seamlessly? This would be perfect for something im working on. And taking it a step further:) Its able to detect if its a jpg and swf and render the mark up accordingly?

    thanks in advance

  6. casyno August 6, 2008 5:34 pm

    casyno...

    overhangs clumsiness,porcupines:prosecutions ...

Leave a Comment

If you would like to make a comment, please fill out the form below.

Name (required)

Email (required)

Website

Comments

Attention
If you want to post source code, please wrap it with <pre> and </pre>

Categories

Polls

  • Which browser are you using to browser this site?

    View Results

    Loading ... Loading ...