Lazy loading

Lazy loading is a way to optimize web page performance, which can greatly improve the user experience. Images have always been a major contributor to web performance, and now it’s not uncommon for a single image to exceed a few megabytes. If you ask for all images every time you come to the page, chances are the user will be gone by the time the images load. So when you enter the page, only request images from the viewable area.

The summary is:

  • Reduce the load of resources, the page only load the first screen image, this can significantly reduce the server pressure and traffic, also can reduce the burden of the browser.
  • Prevent the concurrent loading of too many resources and block JS loading, affect the whole website startup, affect the user experience
  • Waste of user traffic, some users do not want to read all, all load will consume a lot of traffic.

The principle of

The principle of lazy image loading is to hide the URL of the image temporarily without setting the SRC attribute of the image. For example, write the URL of the image in data-src first, and then put the real URL of the image into the SRC attribute after the current image is in the visible area, so as to realize the lazy image loading.

  function lazyload(){
    let imgs = document.querySelectorAll('img[data-src]')
    imgs.forEach((item,index) = > {
        let clientHeight = document.documentElement.clientHeight
        let scrollTop = document.documentElement.scrollTop
        if(item.dataset.src === ' ') return
        if( item.offsetTop - scrollTop < clientHeight){
            item.src = item.dataset.src
            item.removeAttribute('data-src')}}}window.addEventListener('scroll', lazyload)

Copy the code

Through the implementation of the above example, if we want to realize lazy loading, we need to listen for scroll events. Although we can prevent high frequency function execution by function throttling, we still need to calculate the properties of scrollTop,offsetHeight and so on. Is there a simple way not to calculate these attributes? The answer is yes –IntersectionObserver

const imgs = document.querySelectorAll('img[data-src]')
const config = {
  rootMargin: '0px'.threshold: 0,}let observer = new IntersectionObserver((entries, self) = > {
  entries.forEach((entry) = > {
    if (entry.isIntersecting) {
      let img = entry.target
      let src = img.dataset.src
      if (src) {
        img.src = src
        img.removeAttribute('data-src')}// Remove the observation
      self.unobserve(entry.target)
    }
  })
}, config)

imgs.forEach((image) = > {
  observer.observe(image)
})

Copy the code