Preloading css images using jQuery

Does anyone know a good way to preload css hover images using jQuery?

Ideally, I would like to add a class (say, " pre-load-hover ") to any element that needs to be preloaded, and then put some js in $(document).ready() to cycle through any DOM elements with with this class, find their css background image and load it.

The problem is that I cannot find a way to easily get to the location of the image hover. The jQuery :hover selector does not seem to work.

I also do not want to load all the stylesheets and look for the selector with some string search.

+4
source share
6 answers

I think you should try CSS sprites. This is a method in which you use a single image that contains both a normal image and a hover image. Then you just play with the edge (using negative margin) to show the corresponding image. You can read this article about CSS sprites .

+7
source

This is a small snapshot that I use to preload images:

 preload = (function () { var images = []; return function () { var args = Array.prototype.slice.call(arguments); while (args.length > 0) { images.unshift(new Image()); images[0].src = args.shift(); } } }()); 

Using:

 preload('http://example.com/some_image.png' /* , 'http://example.com/some_other_image.png' ... */); preload.apply(this, ['http://example.com/some_image.png' /* , 'http://example.com/some_other_image.png' ... */]); 
+3
source

You can take a look here:

This is a special plugin for jquery.

http://plugins.jquery.com/project/automated_image_preloader

+1
source

There are several plugins for this already , check them out. For the other part :hover not a valid selector, and not when requesting other elements (to a large extent, always avoid using it in a selector, as it does not work in a cross browser).

+1
source

You can take your sprites one step further and make them a sheet and request images by coordinates. Large companies such as Google and Yahoo do this to reduce server requests (because they use only one image request to display multiple images).

Google Help Sprite Example

Calling specific images with coordinates in CSS:

 .image1 { background: url(spritesheet.png) -30px -30px no-repeat; height: 30px; width: 30px; } .image2 { background: url(spritesheet.png) -120px -50px no-repeat; height: 30px; width: 30px; } 

Put some space between the icons because some mobile browsers (like Safari on iPad) have problems with correctly cutting the background image.

0
source

http://binarykitten.me.uk/dev/jq-plugins/11-jquery-image-preloader.html usage: $ .preLoadImages (['/ images / 1.png', '/images/2.png', '/images/3.png']);

0
source

All Articles