Leahcim
Leahcim

Reputation: 41919

JavaScript Image Preload

I'm looking at how a site DoNothingFor2Minutes preloads its images with JavaScript and it's given rise to a few questions. I noticed that the site doesn't preload all of its images. Indeed, some of the first images you might see on the site aren't preloaded, including both the background image (of the sea and sun) and the title image (which says "do nothing for 2 minutes")

1) is there a reason why you wouldn't preload the images that are used immediately on the page?

2) does it make sense or is it even possible to preload background images?

3) when I view the page source, I see many images that weren't preloaded, but not images that were preloaded (with the exception of spread-the-calm.png). Is there some reason preloaded images aren't in the page source?

Thanks for helping out. I'm a bit of a newbie

var preload = function(sources) {
          var images = [];
          var length = sources.length;
          for(var i = 0;  i < length; i++) {
            images[i] = new Image();
            images[i].src = sources[i];
          }
        }

        preload(['facebook.png', 'facebook-hover.png', 'twitter.png', 'twitter-hover.png', 'like-background.png', 'spread-the-calm.png', 'tewy.png', 'tewy-hover.png', 'coderholic.png', 'coderholic-hover.png', 'box.png', 'box-hover.png', 'email-capture.png']);

Upvotes: 0

Views: 1773

Answers (3)

Cody Caughlan
Cody Caughlan

Reputation: 32748

I am guessing that the site is just preloading images that will be used for CSS hovers - so that the user doesnt see any flickering / loading happen when they hover and the on-hover image is not available and has to be loaded.

The site owner figures that for all other images its OK to have them load as part of the normal cycle.

But yes - users particularly notice not smooth hover transitions, so those are being optimized.

Upvotes: 1

wanovak
wanovak

Reputation: 6127

1) Generally you want to preload images that are important and should be seen right away. A giant picture background doesn't seem like it would be necessary to load right away.

2) It is possible, and it really depends on your specific case whether it's practical or not.

3) The developer is then referencing the images from the images array he's created in JavaScript instead of using HTML (e.g., <img src="...

Upvotes: 1

James Allardice
James Allardice

Reputation: 165941

Why would you need to preload images that are referenced directly by the page? They will be requested as references to them are encountered as the source of the page is parsed.

The preloading is likely to be used for images that are displayed, for example, on mouse over of other elements. The preloading means that the images have already been requested, and there won't be a delay while the image downloads. That's probably why you don't see the preloaded images in the HTML.

Upvotes: 1

Related Questions