Will browsers automatically preload URLs in JavaScript variables?
I'm making a site in which I'm using jQuery to change background images on a page. There will be quite a few images substituted through the course of the site.
By decl开发者_如何学JAVAaring variables like this at the beginning of the script, will it preload the images and therefore allow for faster substitution of images? Or, if I do it with too many images (like 50), will it slow things down? or do the variables use too much memory?
Are there any issues you see with this plan, or is there a better way?
var img1 = "url('images/wackawacka.jpg') repeat";
var img2 = "url('images/wabbaawacka.jpg') repeat";
var img3 etc...
If you're just declaring those variables as strings, JavaScript won't preload those images.
Take a look at this article for how to preload images with JavaScript: http://www.techrepublic.com/article/preloading-and-the-javascript-image-object/5214317
Using that method when the document is loaded, you can load all the images into the users' cache after the page loads, so when they switch, they'll be quickly accessible.
Have you thought of CSS sprites? That will significantly speed up image loading and will also improve performance.
Your way is not bad, although you do have to use "new Image", but depending on your use case, you might be better off using image sprites.
http://css-tricks.com/158-css-sprites/
Here is an example image sprite at Google:
http://www.google.com/images/experiments/nav_logo77.png
The idea is to load one image file with multiple icons combined, and then change where the top and left of the image point to.
Update:
Here's a preloadImage function
function preloadImage(src) {
var myImage = new Image();
myImage.src = src;
}
精彩评论