5

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?

4
  • 2
    1st one has three less lines. Commented Apr 20, 2012 at 22:22
  • cant you just preload them by having them as img tags in a hidden div? or is this for dynamically added elements or is doing it with js a better way? Commented Apr 20, 2012 at 22:22
  • 1
    While the answer is most likely #2 for the reasons below, it would be a good exercise if you measured this yourself by creating two html files that use the different methods to load several dozen, or even several hundred images. You can measure this yourself by using firebug/yslow. Commented Apr 20, 2012 at 22:30
  • @moses that's a damn good idea. think i'll have a play with that on monday. OT: i do love yslow, although i really wish they'd ironically get off their arses to update it a bit quicker when firefox releases a new major version. it was out of action for months when ff9 came out (or was it 10?) Commented Apr 20, 2012 at 22:51

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

'bloatware' is a little strong of jQuery in general, but +1 nonetheless: in this case using jQuery certainly is pointless bloat.
I agree that including jQuery just to do this one task is overkill, but why do you assume it isn't also used for a bunch of other things?
1

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.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.