JaPerk14
JaPerk14

Reputation: 1664

Creating several image objects in JavaScript

I'm programming in JavaScript and I would like to know if there is a 'best' method of creating multiple image objects. Take the code below as an example.

var a = new Image();
var b = new Image();
var c = new Image();

Is this the only way to do it, or should I do something like...

var a = new Image(), b = a, c = a;

I'm just wondering if there is a different way of doing the first method. I find my program contains a lot more 'new Image()' variables, and I thought being repetitive was bad for the code.

Upvotes: 3

Views: 5034

Answers (3)

RadicalRaid
RadicalRaid

Reputation: 1006

I'm not sure I understand your question correctly. I don't believe there is anything wrong with declaring three variables as three different new Image() at all, if the code requires it. In fact, I'm very much for it, because it makes the code more readable in my opinion.

However, if you're set on doing it somewhat different you could try this:

var a = new Image(), b = a.cloneNode( true ), c = a.cloneNode( true );

I don't think this is very readable though.

You could also try initialising them in a list which is probably the preferred method, if the code allows this.

var images = [];
for( var index = 0; index < 10; index++ ) {
    images.push( new Image() );
}

Upvotes: 2

LetterEh
LetterEh

Reputation: 26696

The second way is the same image.

If you say that:

b = a;
c = b;

And if a is an object, then b and c are just references which point to the same object.

How about making a function to load an image?

function loadImage(name, optionalCallback) {
    var img = new Image();
    if (typeof optionalCallback === "function") { img.onload = optionalCallback; }
    img.src = name;

    return img;
}

Then you can say:

var a = loadImage("images/image01.png", function () { document.body.appendChild(this); }),
    b = loadImage("images/image02.jpg", function () { gallery.addImage(this); });

There's a lot more that you can do with this, when you get further along -- when you get into Promises and whatnot, you can do an awful lot with those images.

Also, you might want to be careful if you're writing a program that looks like:

var a = new Image();
a.src = "images/image01.jpg";
document.getElementById("gallery").appendChild(a);

If you get to the part of the code where you're adding the image to the page, before the image is done loading, then you might get unexpected results.

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270617

I would probably build them as an array, rather than pollute your namespace with a pile of separate variables pointing to different Image objects.

var imgs = [];
var numImgs = 10;
// In a loop, build up an array of Image objs
for (var i=0; i<numImgs; i++) {
  imgs.push(new Image());
  // Initialize properties here if necessary
  imgs[i].src = 'http://example.com';
}
// imgs now holds ten Image objects...
// Access them via their [n] index
img[3].src = 'http://stackoverflow.com';

This isn't going to be much more or less efficient than creating multiple variables, but it is certainly easier to keep them organized. You will save a few lines of code in initializing them, but in the long run, that amounts to a micro-optimization which will have only negligible effect.

Note that if you really want a text descriptor for each Image, you could opt to use an object {} instead of an Array [] and set its properties to small descriptive strings. You could even initialize it via an array:

var imgNames = ['stackoverflow','google','example'];
var imgs = {}
// Initialize object properties in a loop
for (var i=0; i<imgNames; i++) {
  // Initialize a property in the object from the current array value using [] notation
  imgs[imgNames[i]] = new Image();
}
// Then you can access them by their property name:
imgs.google.src = 'http://www.google.com';
imgs.stackoverflow.src = 'http://stackoverflow.com';

This borders a little on misuse of the object to behave like a PHP or Perl associative array, but will provide easy access to the images if you need them by name rather than a numeric key as in the array method above.

Upvotes: 1

Related Questions