Javascript image preload strategy
Like many people I've been doing image preload for a long time, but not always very rationally. So I've come up with this short list of thoughts about the right way to preload images with javascript.
- An image preload script should be executed as soon as possible. It should be placed at the top of the HTML (in the HEAD section), unlike the others scripts that go to the bottom of the BODY section.
- It must not rely on a library (such as jQuery) because that would delay the execution.
- CSS sprites and background-images need not be preloaded because the CSS - normally called at the top of the HTML - already does the job (this of course reduces the overall need for javascript image preload).
- The preload script can be placed and run on every page of the site so as to be sure it is effective no matter which page th开发者_JS百科e user enters the site. (But what about the overhead of running the script every time, if only to check the images are now cached?)
I'd be very interested to hear your opinions on this subject.
An image preload script should be executed as soon as possible. It should be placed at the top of the HTML (in the HEAD section), unlike the others scripts that go to the bottom of the BODY section.
This puts greater precedence on images that might be shown if the user does something then on images which are part of the initial page. (Unless you are trying to preload images which are part of the initial page, which would be redundant).
It must not rely on a library (such as jQuery) because that would delay the execution.
Such a delay shouldn't be significant
CSS sprites and background-images need not be preloaded because the CSS - normally called at the top of the HTML - already does the job (this of course reduces the overall need for javascript image preload).
Browsers may optimize and not load images mentioned in stylesheets if they aren't being displayed.
The preload script can be placed and run on every page of the site so as to be sure it is effective no matter which page the user enters the site. (But what about the overhead of running the script every time, if only to check the images are now cached?)
Sensible cache control headers should avoid the need to make HTTP requests to check the freshness of images, so this should be negligible.
精彩评论