views:

193

answers:

2

I am seeing a lot of sites these days, mainly tutorial sites that have a lot of images and they only load images further down the page once they come into the view port?

How would I go about doing this?

An example:

http://www.chopeh.com/blog/logo-design-start-to-finish/

As you scroll down the page the images below the view port fade in

+4  A: 

http://www.appelsiini.net/projects/lazyload

Demo:
http://www.appelsiini.net/projects/lazyload/enabled.html

z5h
brilliant, thanks!
Colin
+2  A: 

Replace your images with placeholders (e.g. just change the "src" attribute to something else so the image won't load, but the url will still be accessible), and then bind the window scroll event to a function which will find all images at the current scroll position, and swap the image src into a real img tag.

Here's the code. It's untested, but this should be the basic idea:

<img src="" realsrc="/myimage.png" />

$(document).ready(function(){

  $(window).scroll(function(){
    $('img[realsrc]').each(function(i){
      var t = $(this);
      if(t.position().top > ($(window).scrollTop()+$(window).height()){
        t.attr('src', t.attr('realsrc')); // trigger the image load
        t.removeAttr('realsrc'); // so we only process this image once
      }
    });
  })

});
Chris S
for some info on how to actually do scrolling detection, see this page: http://codepunk.hardwar.org.uk/ajs02.htm
Igor