David542
David542

Reputation: 110163

More efficient way to pre-load images

What is a better way to pre-load images:

$.each(['{{ MEDIA_URL }}jwplayer/jwplayer.js',
        '{{ MEDIA_URL }}jwplayer/jwplayer.js.jgz',
        '{{ MEDIA_URL }}jwplayer/player.swf'], function() {
   $('<img/>')[0].src = this;

or:

var preloadImages = ['{{ MEDIA_URL }}jwplayer/jwplayer.js',
                     '{{ MEDIA_URL }}jwplayer/jwplayer.js.jgz',
                     '{{ MEDIA_URL }}jwplayer/player.swf'];
var imgs = [];
for (var i=0; i<preloadImages.length; i++) {
    imgs[i] = new Image();
    imgs[i].src = preloadImages[i];
}

What makes one better than the other?

Upvotes: 5

Views: 356

Answers (3)

jfriend00
jfriend00

Reputation: 707328

The second is faster. The first is less typing (by using a higher level iterator method in jQuery).

If you already have jQuery in your project for other reasons, then which is better depends upon whether you'd rather optimize for speed or code size.

On a technical level, there's one actual implementation difference. The second version keeps an array of the image objects around in a variable. The first lets the image objects get garbage collected.

Upvotes: 1

wsanville
wsanville

Reputation: 37516

Both do the same thing. The first snippet is using jQuery, and the second does not. There's no reason to use jQuery exclusively for this purpose, so if you're not using the library elsewhere, go with the second version. If you're using jQuery throughout your site, then the first is ok too.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

The second is better than the first, because it's plain JavaScript versus the excessive bloatware of jQuery.

You can improve the second one a little, by setting l=preloadImages.length up front and using that in the loop.

Upvotes: 7

Related Questions