Javascript image lazy loading and pre-loading analysis

Source: Internet
Author: User

Basic concepts of lazy loading and pre-loading. Lazy loading is also called delayed loading: the previous article introduced the delay loading of JS images. Some images are loaded only when the image loading is delayed or meets certain conditions. Pre-loading: The image is loaded in advance. You can directly render the image from the local cache when you need to view it. The essence of the two technologies: the two are the opposite. One is to load ahead, and the other is to load slowly or even not. Lazy loading can reduce the pressure on the front-end of the server. preloading will increase the pressure on the front-end of the server. The significance and implementation methods of lazy loading are as follows: The main purpose of lazy loading is to optimize the server front-end and reduce the number of requests or the number of delayed requests. Implementation Method: 1. the first type is purely delayed loading. setTimeOut or setInterval is used for loading latency. 2. the second is conditional loading, which meets certain conditions or triggers some events to start asynchronous download. 3. the third type is visible area loading, that is, loading only the area that the user can see. This is mainly implemented by the monitoring scroll bar, which usually starts loading at a certain distance before the user can see an image, this ensures that the user can see the image properly when pulling it down. The significance and implementation methods of pre-loading are as follows: pre-loading can be said to sacrifice the server's front-end performance in exchange for a better user experience, so that users' operations can be reflected as quickly as possible. Many pre-loading methods can be implemented using CSS (background), JS (Image), and HTML (. The commonly used method is new Image ();. set its src to implement the preload, and then use the onload method to call back the event to complete the preload. As long as the browser downloads the image to the local, the same src will use the cache, which is the most basic and practical pre-loading method. After the Image header is downloaded, the width and height are obtained. Therefore, the Image size can be obtained before pre-loading (the rotation width and height are used to change ). How can we implement pre-loading? We can search by google: we can see that many people use this method for pre-loading: the code is as follows: copy the code function loadImage (url, callback) {var img = new Image (); img. src = url; img. onload = function () {img. onload = null; callback. call (img) ;}} copying code in google or Firefox is normal, no matter how I refresh it, it is normal, however, if this is not the case in IE6, it is normal to click again or refresh again. The following jsfiddle address: If you are interested, you can click the button and the normal result will pop up. If you click again under IE6, the method in onload will not be executed, and then refresh it again. To see the effect, click me! Why are other browsers normal? The reason is that the browser is cached, except for IE6 (that is, opera also works, but I tried it with opera specially. No, maybe the version has been fixed .), The onload method will be executed again when other browsers Click again, but IE6 is taken directly from the browser. What should we do now? The best case is that the Image may have a status value indicating whether it has been loaded successfully. When loading from the cache, because you do not need to wait, this status value directly indicates that it has been downloaded. When loading from an http request, this value is not displayed because you need to wait for download. In this way, you can do it. After a google search, we found that there is a complete attribute compatible with the Image of each browser. Therefore, make a judgment on this value before the image onload event. Finally, the Code looks like this: copy the code function loadImage (url, callback) {var img = new Image (); img. src = url; if (img. complete) {// if the image already exists in the browser cache, call the callback function callback directly. call (img); return; // direct return, no need to process onload event} img. onload = function () {img. onload = null; callback. call (img) ;}}: if the image is already in the browser cache, you can directly obtain the image from the browser cache and execute img. the functions in complete are returned. but we can see the above Code: After the image is loaded, you can execute the callback function. You can also say that after the image is loaded, we can get the width and height of the image. So what if we want to get the image size in advance? Internet experience tells me: when the browser loads an image, you will see that the image occupies a space before loading the image. You do not need to preset the width and height attributes, because the browser can obtain the header data of the image. Based on this, you only need to use javascript to regularly detect the size status of the image to know that the image size is ready. The Code is as follows: (but there is a premise that this method is not what I think, it is not the code I write, it is the code summarized by online friends, I just know that there is such a principle) copy the code var imgReady = (function () {var list = [], intervalId = null; // run the 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, the cached data if (img. complete) {ready. call (img); return;} width = img. width; height = img. height; // load the error event img. onerror = function () {error & error. call (Img); onready. end = true; img = img. onload = img. onerror = null ;}; // The image size is ready. var onready = function () {newWidth = img. width; newHeight = img. height; if (newWidth! = Width | newHeight! = Height | // if the image has been loaded elsewhere, use area detection newWidth * newHeight> 1024) {ready. call (img); onready. end = true ;};}; onready (); // fully loaded event img. onload = function () {// onload may be faster than onready In the timer time difference range. // check here and ensure that onready is executed preferentially! Onready. end & onready (); // The ie gif animation executes onload cyclically and sets the onload value to img = img. onload = img. onerror = null ;}; // periodically execute if (! Onready. end) {list. push (onready); // only one timer is allowed at a time to reduce browser performance loss if (intervalId = null) {intervalId = setInterval (queue, 40) ;};}}) (); copy the code to call imgReady ('HTTP: // using () {alert ('width: '+ this. width + 'height: '+ this. height );});

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.