Advertisement
rg443

LAZY Loading Images - Javascript without framework

Jan 19th, 2013
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //
  2. //  LAZY Loading Images
  3. //
  4. //  Handles lazy loading of images in one or more targeted divs,
  5. //  or in the entire page. It also keeps track of scrolling and
  6. //  resizing events, and removes itself if the work is done.
  7. //
  8. // http://stackoverflow.com/questions/3228521/stand-alone-lazy-loading-images-no-framework-based
  9.  
  10. (function(){
  11.  
  12. // glocal variables
  13. var window    = this,
  14.     instances = {},
  15.     winH;
  16.  
  17. // cross browser event handling
  18. function addEvent( el, type, fn ) {
  19.   if ( window.addEventListener ) {
  20.     el.addEventListener( type, fn, false );
  21.   } else if ( window.attachEvent ) {
  22.     el.attachEvent( "on" + type, fn );
  23.   } else {
  24.     var old = el["on" + type];
  25.     el["on" + type] = function() { old(); fn(); };
  26.   }
  27. }
  28.  
  29. // cross browser event handling
  30. function removeEvent( el, type, fn ) {
  31.   if ( window.removeEventListener ) {
  32.     el.removeEventListener( type, fn, false );
  33.   } else if ( window.attachEvent ) {
  34.     el.detachEvent( "on" + type, fn );
  35.   }
  36. }
  37.  
  38. // cross browser window height
  39. function getWindowHeight() {
  40.   if ( window.innerHeight ) {
  41.     winH = window.innerHeight;
  42.   } else if ( document.documentElement.clientHeight ) {
  43.     winH = document.documentElement.clientHeight;
  44.   } else if ( document.body && document.body.clientHeight ) {
  45.     winH = document.body.clientHeight;
  46.   } else {        // fallback:
  47.     winH = 10000; // just load all the images
  48.   }
  49.   return winH;
  50. }
  51.  
  52. // getBoundingClientRect alternative
  53. function findPos(obj) {
  54.   var top  = 0;
  55.   if (obj && obj.offsetParent) {
  56.     do {
  57.       top += obj.offsetTop || 0;
  58.       top -= obj.scrollTop || 0;
  59.     } while (obj = obj.offsetParent); //
  60.     return { "top" : top };
  61.   }
  62. }
  63.  
  64. // top position of an element
  65. var getTopPos = (function() {
  66.   var dummy = document.createElement("div");
  67.   if ( dummy.getBoundingClientRect ) {
  68.     return function( el ) {
  69.       return el.$$top || el.getBoundingClientRect().top;
  70.     };
  71.   } else {
  72.     return function( el ) {
  73.       return el.$$top || findPos( el ).top;
  74.     };
  75.   }
  76. })();
  77.  
  78. // sorts images by their vertical positions
  79. function img_sort( a, b ) {
  80.   return getTopPos( a ) - getTopPos( b );
  81. }
  82.  
  83. // let's just provide some interface
  84. // for the outside world
  85. var LazyImg = function( target, offset ) {
  86.  
  87.   var imgs,    // images array (ordered)
  88.       last,    // last visible image (index)
  89.       id,      // id of the target element
  90.       self;    // this instance
  91.  
  92.   offset = offset || 200; // for prefetching
  93.  
  94.   if ( !target ) {
  95.     target = document;
  96.     id = "$document";
  97.   } else if ( typeof target === "string" ) {
  98.     id = target;
  99.     target = document.getElementById( target );
  100.   } else {
  101.     id = target.id || "$undefined";
  102.   }
  103.  
  104.   // return if this instance already exists
  105.   if ( instances[id] ) {
  106.     return instances[id];
  107.   }
  108.  
  109.   // or make a new instance
  110.   self = instances[id] = {
  111.  
  112.     // init & reset
  113.     init: function() {
  114.       imgs = null;
  115.       last = 0;
  116.       addEvent( window, "scroll", self.fetchImages );
  117.       self.fetchImages();
  118.       return this;
  119.     },
  120.  
  121.     destroy: function() {
  122.       removeEvent( window, "scroll", self.fetchImages );
  123.       delete instances[id];
  124.     },
  125.  
  126.     // fetches images, starting at last (index)
  127.     fetchImages: function() {
  128.  
  129.       var img, temp, len, i;
  130.  
  131.       // still trying to get the target
  132.       target = target || document.getElementById( id );
  133.  
  134.       // if it's the first time
  135.       // initialize images array
  136.       if ( !imgs && target ) {
  137.  
  138.         temp = target.getElementsByTagName( "img" );
  139.  
  140.         if ( temp.length ) {
  141.           imgs = [];
  142.           len  = temp.length;
  143.         } else return;
  144.  
  145.         // fill the array for sorting
  146.         for ( i = 0; i < len; i++ ) {
  147.           img = temp[i];
  148.           if ( img.nodeType === 1 && img.getAttribute("thumb") ) {
  149.  
  150.               // store them and cache current
  151.               // positions for faster sorting
  152.               img.$$top = getTopPos( img );
  153.               imgs.push( img );
  154.           }
  155.         }
  156.         imgs.sort( img_sort );
  157.       }
  158.  
  159.       // loop through the images
  160.       while ( imgs[last] ) {
  161.  
  162.         img = imgs[last];
  163.  
  164.         // delete cached position
  165.         if ( img.$$top ) img.$$top = null;
  166.  
  167.         // check if the img is above the fold
  168.         if ( getTopPos( img ) < winH + offset )  {
  169.  
  170.           // then change the src
  171.           img.src = img.getAttribute("thumb");
  172.           last++;
  173.         }
  174.         else return;
  175.       }
  176.  
  177.       // we've fetched the last image -> finished
  178.       if ( last && last === imgs.length )  {
  179.         self.destroy();
  180.       }
  181.     }  
  182.   };
  183.   return self.init();
  184. };
  185.  
  186. // initialize
  187. getWindowHeight();
  188. addEvent( window, "load",   LazyImg().fetchImages );
  189. addEvent( window, "resize", getWindowHeight       );
  190. LazyImg();
  191.  
  192. window.LazyImg = LazyImg;
  193.  
  194. }());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement