Home  >  Article  >  Web Front-end  >  Example of lazy loading of images using javascript

Example of lazy loading of images using javascript

陈政宽~
陈政宽~Original
2017-06-28 12:49:431242browse

Image lazy loading is also a relatively common Performance Optimization method. This article mainly introduces the native JS implementation of image lazy loading (lazyload) examples. Here is a detailed code, if necessary Friends, you can refer to

Preface

Lazy loading of images is also a relatively common performance optimization method. Recently, I am using vue to make one It is also used in the client of the news list. Here is a brief introduction to the implementation principle and part of the code.

Implementation Principle

When loading a page, pictures are always the main source of traffic, and there are many performance methods for pictures, such as base64, Sprite pictures, etc.; lazy loading is also one of them. The main principle is to set the src of the non-first-screen picture to a default value, then monitor the window scrolling, and then give it a real picture address when the picture appears in the window. This can Ensure the loading speed of the first screen and then load images on demand.


Specific code

First when rendering, the pictureQuoteDefault image, and then put the real address on the data-* attribute.

Then to monitor scrolling, just use window.onscroll. However, one thing to note is scroll and resize similar to window, and events like mousemove that are triggered frequently, it is best to use throttling or anti-shake function (debounce) to control the trigger frequency. There are two methods of encapsulation in underscore and lodash, so I won’t introduce them in detail here.

The next step is to determine whether the image appears in the window, mainly based on three heights: 1. How far the current body has scrolled from the top. 2. The height of the window. 3. The distance between the current picture and the top. The specific code is as follows:


window.onscroll =_.throttle(this.watchscroll, 200);
watchscroll () {
  var bodyScrollHeight = document.body.scrollTop;// body滚动高度
  var windowHeight = window.innerHeight;// 视窗高度
  var imgs = document.getElementsByClassName('lazyloadimg');
  for (var i =0; i < imgs.length; i++) {
  var imgHeight = imgs[i].offsetTop;// 图片距离顶部高度
  if (imgHeight < windowHeight + bodyScrollHeight) {
   imgs[i].src = imgs[i].getAttribute('src');
   img[i].className = img[i].className.replace('lazyloadimg','')
  }
  }
 }


The above is the detailed content of Example of lazy loading of images using javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn