Question

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.

Was it helpful?

Solution

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);
}

OTHER TIPS

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.

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/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top