Code solutions to PHP, JS, CSSCode source PHP, JS, CSS

Spread your code soluces to the world

Love me
Solucior » JAVASCRIPT » Load image with page scroll.Lazy loading

Load image with page scroll.Lazy loading

10/02/2014 by Dux   -   not rated

Images are displayed only when they are in the visible area of the window (lazy loading). The code work with the page scrolling. You dont need to modify your HTML code. You can replace the favicon.gif by a blank gif/png.

See a demonstration of this script in action :

Open in a new window     Open in the same window

source code



 
/*********** Lazy Loading ****************/

// Delete SRC
function lazyClean() {
       var
tabimg = document.getElementsByTagName('img');
       for (var
i = 0, l = tabimg.length; i < l; i++) {
               
// Add data-src and display a default image src
               
tabimg[i].dataset.src = tabimg[i].src
               tabimg
[i].src = '../i/favicon.gif';
       }
       
// display image with its src
       
lazyload();
       
document.onscroll = lazyload ;
}

// Lazy Load
function lazyload(){
       var
winTop = document.body.scrollTop;
       var
winH = window.innerHeight;
       var
tabimg = document.getElementsByTagName('img');
       for (var
i = 0, l = tabimg.length; i < l; i++) {
               if(
tabimg[i].offsetTop < (winTop + winH + 1) ) tabimg[i].src = tabimg[i].dataset.src;
       }
}
window.onload = lazyClean;

Tested with Safari  Google Chrome  Firefox3  Firefox4  
Rate this code     |     Copied : 4x

Comments for Load image with page scroll.Lazy loading

No comment
Add a comment Nickname
ZOOM


Zoom with CSS3
Div following the scrolling of the page
Simple image gallery PHP
Javascript opacity
Adjust the rate of image colors
Scroll div with javascript
Show hide DIV content with scrolling
Automatically adjust brightness contrast of an image
Make dir and upload files via FTP
Dynamically resizing height of textarea