Optimising image fade swap code

Optimising image fade swap code


I have this code that currently swaps an image in the background of my site using two divs with a fade in effect. The code also vertically centers the image.

This code works absolutely fine on a local server but as soon as its uploaded it becomes a little jerky and sometimes the vertical align 'misfires' and the top margin is far too big.

  1. function fadeBackground(image) {
  2.      $('#wrapper_2 img').attr('src', image).load(function() { 
  3.                                                              
  4.     var border = ($(window).height() - $('#wrapper_2 img').outerHeight())/2;
  5.     $('#wrapper_2 img').css("margin-top", border);
  6.          
  7.     });
  8.        
  9.         $('#wrapper_2').css('background-color', $backgroundcolour);       
  10.         $('#wrapper_2').fadeIn('slow', function() {
  11.        
  12.                                                              
  13.         $('#wrapper_1').css( 'background-color', $backgroundcolour);
  14.         $('#wrapper_1 img').attr('src', image);
  15.        
  16.         var border2 = ($(window).height() - $('#wrapper_1 img').outerHeight())/2;
  17.         $('#wrapper_1 img').css("margin-top", border2);
  18.        
  19.         $('#wrapper_2').css('display', 'none');
  20.         $('#wrapper_1').css('display', 'block');
  21.            
  22. });
  23.        
  24. }

I have included the .load function to make sure the image is loaded but this didn't work with the second time I call the image:

  1.         $('#wrapper_1 img').attr('src', image);
I suspect because the image has already loaded into cache (as its a duplicate of the first image call) so it doesn't fire a second .load event?

Is it possible to optimise this code further to make sure the images fade a little smoother and that the css margin doesn't happen too early?

Also using:

  1. <img src=""/>
seems to produce a question mark placeholder once the site has been uploaded - how do I prevent this?

Thanks