Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 248
David542 Avatar asked Apr 20 '12 22:04

David542


2 Answers

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.

like image 99
Niet the Dark Absol Avatar answered Sep 21 '22 23:09

Niet the Dark Absol


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.

like image 21
wsanville Avatar answered Sep 22 '22 23:09

wsanville