English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Analysis and summary of JavaScript lazy loading and preloading of images

This article mainly introduces the analysis of two technologies: lazy loading and preloading. There is no need to talk about unnecessary things, let's take a look together.

Lazy loading is also called delayed loading:The previous article has introduced: JS image lazy loading, loading certain images only when certain conditions are met or triggered.

Preloading:Preload images, so that when the user needs to view them, they can be rendered directly from the local cache.

The essence of the two technologies:Their behaviors are opposite. One is to load in advance, and the other is to delay or not load at all. Lazy loading has a certain alleviating effect on the pressure of the server front-end, while preloading will increase the pressure of the server front-end.

The significance and implementation methods of lazy loading are:

Significance: The main purpose of lazy loading is to optimize the server front-end, reduce the number of requests or delay the number of requests.

Implementation methods:

1.The first is pure delay loading, using setTimeOut or setInterval for loading delay.

2.The second is conditional loading, which starts asynchronous downloading when certain conditions are met or certain events are triggered.

3.The third is visible area loading, which means only loading the area that the user can see. This is mainly realized by monitoring the scroll bar, and generally starts loading a certain distance before the user sees the image, so that it can ensure that the user can see the image when they scroll down.

The significance and implementation methods of preloading are:

Preloading can be said to be sacrificing the performance of the server front-end in exchange for a better user experience, so that the user's operation can get the fastest response. There are many ways to implement preloading, such as CSS(background), JS(Image), HTML(<img /It can all be done. The commonly used method is new Image();, set its src to achieve preloading, and then use the onload method to call back the preloading completion event. As long as the browser downloads the image to the local machine, the same src will use the cache, which is the most basic and practical preloading method. When the Image downloads the image header, it will get the width and height, so the size of the image can be obtained before preloading (the method is to use a timer to cycle through the changes in width and height).

How can we achieve preloading?

We can search on Google: We can see that many people use this method for preloading: the code is as follows:

 function loadImage(url, callback) {
  var img = new Image();
  img.src = url;
  img.onload = function() {
    img.onload = null;
    callback.call(img);
  }
}

Why are other browsers normal: The reason is very simple, it is because the browser caches, except for IE6Other browsers will execute the onload method again when clicked again, but IE6It is directly obtained from the browser.

So what should we do now? The best scenario is that Image can have a status value indicating whether it has been successfully loaded. When loading from the cache, since there is no need to wait, this status value directly indicates that it has been downloaded, and when loading from an HTTP request, since it needs to wait for the download, this value shows as incomplete. In this way, we can solve the problem. After searching on Google, I found that there is an attribute of Image that is compatible with all browsers - complete. So, before the image onload event, we can make a judgment on this value. Finally, the code becomes as follows:

function loadImage(url, callback) {
  var img = new Image();
  img.src = url;
  if(img.complete) { // If the image already exists in the browser cache, directly call the callback function
    callback.call(img);
    return; // Just return directly, no need to handle the onload event again
  }
  img.onload = function() {
    img.onload = null;
    callback.call(img);
  }
}

That is to say, if the image is already in the browser cache, then it is possible to directly execute the function inside img.complete from the browser cache and then return.

But we can see the code above: we must wait for the image to be fully loaded before we can execute the callback function, or we can say that after the image is loaded, we can obtain the width and height of the image. So what if we want to get the image size in advance? My internet experience tells me: when the browser is loading an image, you will see that the image first occupies a space and then loads slowly until it is complete, and there is no need to set the width and height attributes in advance, because the browser can obtain the header data of the image. Based on this, we only need to use JavaScript to detect the size status of the image at regular intervals to know when the image size is ready. The code is as follows: (However, there is a premise that this method is not what I thought of, nor is it the code I wrote; it is a code summarized by an internet friend, and I just know about this principle)

var imgReady = (function(){
  var list = [],
    intervalId = null;
  // Used to execute the queue
  var queue = function(){
    for(var i = 0; i < list.length; i++{
      list[i].end ? list.splice(i--,1) : list[i]();
    }
    !list.length && stop();
  };
  // Stop all timer queues
  var stop = function(){
    clearInterval(intervalId);
    intervalId = null;
  }
  return function(url, ready, error) {
    var onready = {}, 
      width, 
      height, 
      newWidth, 
      newHeight,
      img = new Image();
    img.src = url;
    // If the image is cached, return the cached data directly
    if(img.complete) {
      ready.call(img);
      return;
    }
    width = img.width;
    height = img.height;
    // Event after loading error 
    img.onerror = function () {
      error && error.call(img);
      onready.end = true;
      img = img.onload = img.onerror = null;
    };
    // Image size ready
    var onready = function() {
      newWidth = img.width;
      newHeight = img.height;
      if (newWidth !== width || newHeight !== height ||
        // If the image has already been loaded elsewhere, you can use area detection
        newWidth * newHeight > 1024
      ) {}}
        ready.call(img);
        onready.end = true;
      };
    };
    onready();
    // The event of complete loading
    img.onload = function () {
      // onload may be faster than onready within the timer time difference
      // Check here and ensure that onready is executed first
      !onready.end && onready();
      // IE gif animation will loop execute onload, set onload to null
      img = img.onload = img.onerror = null;
    };
    // Join the queue to execute regularly
    if (!onready.end) {
      list.push(onready);
      // Only one timer is allowed at any time to reduce browser performance loss
      if (intervalId === null) {
        intervalId = setInterval(queue, 40);
      };
    };
  }
})();

The calling method is as follows:

imgReady('http://img01.taobaocdn.com/imgextra/i1/397746073/T2BDE8Xb0bXXXXXXXX-397746073.jpg',function(){
  alert('width:' + this.width + 'height:' + this.height);
});

That's all for this article. I hope this article is helpful to you, and I hope everyone will continue to pay attention to our website! If you want to learn JSP, you can continue to pay attention to this site.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You May Also Like