More efficient way to preload images

What is better for preloading 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 does better than the other?

+5
source share
3 answers

The second is better than the first because it is simple JavaScript compared to the jQuery redundant virus.

You can improve the second a bit by setting l=preloadImages.lengthin front and using this in a loop.

+7
source

Both are doing the same. The first snippet uses jQuery, and the second not. There is no reason to use jQuery solely for this purpose, so if you are not using the library elsewhere, upgrade to the second version. If you use jQuery on your site, then everything is fine at first.

+1

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

If you already have jQuery in your project for other reasons, then what better depends on whether you want to optimize the speed or size of the code.

At the technical level, there is one real difference in implementation. The second version stores an array of image objects in a variable. The first allows image objects to collect garbage.

+1
source

All Articles