views:

189

answers:

3

I'm now doing something like :

$img.hover(function(){$(this).attr('src','1.jpg')},function(){$(this).attr('src','2.jpg')});

Which is not smooth,because it takes quite some time to load an image.

+4  A: 

Change that to a background image with both the images combined and change the background position dynamically.

Use CSS sprites.

If you need to stick with an image itself then preload the two images and then it will take the second image from the cache which won't cause the delay.

Preloading Images With CSS

rahul
A: 

Try this: Load image and swap when done or Preload image when page load.

NawaMan
+5  A: 

What about pre-loading your images when the page loads:

$(function () {
  var preloadImages = ['1.jpg', '2.jpg'];

  $.each(preloadImages, function () {
    $('<img/>').attr('src', this);
  });

  // ...
});
CMS
Do you prefer this method as opposed to `var img = new Image(); img.src = 'preloadMe.jpg'`? Just wondering as I've always used my example and havn't considered other options.
alex
@alex, Well, the two ways are equivalent, when I have no jQuery on hand, I use something like your example or simply something like this: `(document.createElement('img')).src = 'preloadMe.jpg';`
CMS