1

This is kind of a continuation of a QUESTION I ASKED YESTERDAY and an off-shoot of THIS QUESTION.

Basically, I am using jquery to change css background images on page scroll, however on first visit, when the background changes on scroll it only starts loading then and there making for a poor user experience.

I am using cache headers so that this only happens once, but still it would be nice if it didn't happen at all.

How can I load the second CSS image before the page scrolls to make the transition seamless?

I am only trying to load this one image in the background, not preload all images on the page before display or anything...

Current code I am using...

jquery

jQuery(window).scroll(function(){
var fromTopPx = 200; // distance to trigger
var scrolledFromtop = jQuery(window).scrollTop();
if(scrolledFromtop > fromTopPx){
    jQuery('html').addClass('scrolled');
}else{
    jQuery('html').removeClass('scrolled');
}
});

css

html {
background-repeat: no-repeat;
background-position: center center;
background-attachment: fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

html {
background-image:url(http://robt.info/wp-content/uploads/2013/06/funny-kids-comic-animals.jpg);
}

html.scrolled {
background-image:url(http://robt.info/wp-content/uploads/2013/06/funny-kids-comic-animals_2.jpg);
}

DEMO - Scroll to see in action.

Community
  • 1
  • 1
rob_towner
  • 103
  • 1
  • 1
  • 12
  • I don't want to edit a link to your site, but the background-image for `html.scrolled` is 404'ing. The jsfiddle I referenced has the correct url. – Chris Rockwell Jul 12 '13 at 03:53

3 Answers3

1

Few options here:

  1. Add a hidden element and add your image as a background; the browser will load it and is smart enough to know that it doesn't need to reload

  2. What I would consider the cleaner way: load your second image behind the first one:

html {
    background-image: url(http://robt.info/wp-content/uploads/2013/06/funny-kids-comic-animals.jpg),
                      url(http://robt.info/wp-content/uploads/2013/06/funny-kids-comic-animals_2.jpg);
}

html.scrolled {
    background-image:url(http://robt.info/wp-content/uploads/2013/06/funny-kids-comic-animals.jpg);
}
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
Chris Rockwell
  • 1,688
  • 2
  • 21
  • 36
0

On the left side add all your images and make all of them positioned absolutely

img{
    position :absolute;
    z-index:1;
   }

So all images will be loaded on windows load. And just change their z-index according to scroll.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Haris Amjed
  • 171
  • 1
  • 7
0

One more option is there is to make ur images in a single sprite and display them by changing position..in this way u will save 1 extra http call itself. U can create image sprite with http://spritegen.website-performance.org/

Nitin Agrawal
  • 1,341
  • 1
  • 10
  • 19