A picture lazy loading plug in using jquery (including the principle of picture lazy loading)

  • 2020-03-30 03:10:02
  • OfStack

Lazy loading also called lazy loading images, usually applied to image more web page, if the picture is more, a page and a page there are several screens, height or width page load for the first time, just show the picture of the viewing area, when the page scrolling images into the viewing area again to load, so that can significantly improve the page loading speed, less pictures of concurrent requests can also ease the pressure on the server. Users can also save traffic if they only stay on the first screen. If there are more pictures in the TAB, you can also apply to the TAB, and then load the picture when the TAB is triggered.

The principle of image lazy loading is relatively simple. Firstly, the real address of the image is cached in a custom property (lazy-src), and the SRC address is replaced by a 1 x 1 completely transparent placeholder image. Of course, placeholder image can also be other images.

<img src="images/placeholder.png"  lazy-src="images/realimg.jpg" />

Since javascript is used to load images, if the user has javascript disabled, an alternative can be set.

<img src="images/placeholder.png"  lazy-src="images/realimg.jpg" alt="" />
<noscript><img src="images/realimg.jpg"  alt="" /></noscript>

When the page is first loaded, get the position of the image in the page and cache it (each value of offset will trigger the reflow of the page), calculate the visual area, and when the image position appears in the visual area, replace the value of SRC with the real address, and then the image starts to load.

When the page scrolls, then determine whether the cached position value of the image appears in the visual area, and replace the SRC load. When all images are loaded, unload the corresponding trigger event to avoid memory leaks caused by repeated operations. If the entire window is viewed as a large container, you can also set a small container in the page, which can also achieve lazy loading of images.

The following is the implementation code, I wrote jQuery plug-in.

(function( $ ){
$.fn.imglazyload = function( options ){
 var o = $.extend({
    attr  :   'lazy-src', 
    container  :  window, 
    event   :  'scroll',    
    fadeIn      :   false,    
    threshold  :  0, 
    vertical  :  true 
   }, options ),
  event = o.event,
  vertical = o.vertical,
  container = $( o.container ),
  threshold = o.threshold, 
  //Converting jQuery objects into DOM arrays is easy to manipulate
  elems = $.makeArray( $(this) ),  
  dataName = 'imglazyload_offset',   
  OFFSET = vertical ? 'top' : 'left',
  SCROLL = vertical ? 'scrollTop' : 'scrollLeft',   
  winSize = vertical ? container.height() : container.width(),
  scrollCoord = container[ SCROLL ](),
  docSize = winSize + scrollCoord;

 //Lazy load trigger & NBSP;
 var trigger = {
  init : function( coord ){
   return coord >= scrollCoord && 
                            coord <= ( docSize + threshold );
  scroll : function( coord ){
   var scrollCoord = container[ SCROLL ]();
   return coord >= scrollCoord && 
                    coord <= ( winSize + scrollCoord + threshold );

  resize : function( coord ){
   var scrollCoord = container[ SCROLL ](),
    winSize = vertical ? 
                            container.height() : 
   return coord >= scrollCoord &&
                   coord <= ( winSize + scrollCoord + threshold );

 var loader = function( triggerElem, event ){
  var i = 0,
   isCustom = false,
   isTrigger, coord, elem, $elem, lazySrc;

  //Custom events can be triggered without judgment
  if( event ){
   if( event !== 'scroll' && event !== 'resize' ){
    isCustom = true;
   event = 'init';

  for( ; i < elems.length; i++ ){ 
   isTrigger = false;
   elem = elems[i];
   $elem = $( elem );
   lazySrc = $elem.attr( o.attr );

   if( !lazySrc || elem.src === lazySrc ){
   //First, get the offset value from the cache, and then get the calculated value if there is no value in the cache.
   //Cache the calculated values to avoid reflows caused by repeated fetching
   coord = $elem.data( dataName );

   if( coord === undefined ){
    coord = $elem.offset()[ OFFSET ];
    $elem.data( dataName, coord );
   isTrigger = isCustom || trigger[ event ]( coord );   
   if( isTrigger ){
    //Loading pictures
    elem.src = lazySrc;
    if( o.fadeIn ){
    //Remove the cache
    $elem.removeData( dataName );
    //Removes the DOM from the DOM array
    elems.splice( i--, 1 );
  //Unmount the trigger event after all images are loaded
  if( !elems.length ){
   if( triggerElem ){
    triggerElem.unbind( event, fire );
    container.unbind( o.event, fire );
   $( window ).unbind( 'resize', fire );
   elems = null;


 var fire = function( e ){
  loader( $(this), e.type );

 //The binding event
 container = event === 'scroll' ? container : $( this ); 
 container.bind( event, fire );
 $( window ).bind( 'resize', fire );
 //Initialize the
 return this;
})( jQuery );


$( 'img' ).imglazyload({
 event : 'scroll',
 attr : 'lazy-src'

The default call omits all parameters.
$( 'img' ).imglazyload();

Picture lazy load plug-in API description:

Attr string
The property name of the real address of the image, corresponding to HTML, is lazy-src by default.

The container dom & the selector
The default container is window, which you can customize.

The event stirng
The type of event that triggers the image to load is the default window.onscroll event

FadeIn Boolean
Whether to use the fadeIn effect of jQuery to display, the default is false.

Threshold number
The page loads when it scrolls to the specified distance from the image. The default is 0.

Vertical Boolean
The default value is true(vertical).

LoadScript (enhanced) Boolean
Loading javascript AD images without blocking, false by default.

Related articles: