Analysis of lazy loading and preload of JavaScript pictures

Source: Internet
Author: User
Tags end http request implement return setinterval browser cache


Preload: Loading pictures in advance, rendering them directly from the local cache when they need to be viewed.

The nature of the two technologies: the behavior is reversed, one is in advance, the other is slow or not even loaded. Lazy load on the front end of the server has a certain ease of pressure, preload will increase the front-end pressure on the server.

Lazy loading of the significance and implementation of the way are:

Meaning: Lazy load is the main purpose of the server as a front-end optimization, reduce the number of requests or delay requests.

Implementation mode:

1. The first is a purely delayed load, using settimeout or setinterval for loading delays.

2. The second type is conditional loading, meets certain conditions, or triggers some events before the asynchronous download begins.

3. The third is the visual area loading, that is, only load the area that the user can see, this is mainly by the monitoring scroll bar to achieve, will generally be seen from the user to see a certain distance before the beginning of the load, which can ensure that users pull down when the picture can be seen.

The significance of preload and the way to achieve it are:

Preload can be said to sacrifice server front-end performance, in exchange for a better user experience, so that users can be the fastest response to the action. There are many ways to implement preload, you can use CSS (background), JS (Image), HTML (). Commonly used is the new Image (), set its src to implement preload, and then use the OnLoad method callback preload completion events. As long as the browser to download the picture to the local, the same SRC will use the cache, which is the most basic and practical preload method. When image downloads the head of the picture, it gets wide and high, so you can get the size of the picture before you preload it (the method is to use a timer wheel to follow the width and height change).

How can preload be implemented?

We can search through Google: You can see a lot of people in this way to preload: 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);
}
}



Testing in Google or Firefox is normal, no matter how I refresh it is normal, but not in the IE6 I click on it is normal again click or refresh is not normal. The following Jsfiddle address: Interested students can try to click on the button after the normal results again click on the IE6 do not execute the onload inside the method, and then refresh also not.

Want to see the effect, click me!

Why other browsers are normal: In fact, the reason is very simple, that is, browser caching, in addition to IE6 (that is, opera will also, but I deliberately tried with opera, no, possible version of the problem, perhaps now repaired. , other browsers click again to perform the OnLoad method, but IE6 is directly fetched from the browser.

So what now? The best case scenario is that image can have a status value indicating whether it has been loaded successfully. When loading from the cache, the status value is directly indicated to have been downloaded, and when loading from the HTTP request because it does not need to wait, the value appears to be incomplete. In that case, it will be done. After Google search is introduced: found that there is a browser compatible with the properties of the image--complete. So, before the photo onload event, make a judgment on this value first. Finally, the code becomes as follows:


function LoadImage (url,callback) {
var img = new Image ();

img.src = URL;

if (img.complete) {//If the picture already exists in the browser cache, call the callback function directly

Callback.call (IMG);
Return Return directly without handling the OnLoad event
}

Img.onload = function () {
Img.onload = null;
Callback.call (IMG);
}
}



That is, if the image is already in the browser cache, then the function directly from the browser cache is obtained directly from the Img.complete.

But we can see the above code: you have to wait for the picture to be loaded, you can perform the callback function, you can also say that when the picture is loaded, we can get the width and height of the picture. So what if we want to get the size of the picture in advance? Internet experience tells me: when the browser loads the picture you will see the picture will occupy a piece of land before slowly loading, and do not need to preset width and height properties, because the browser can get the image of the head data. Based on this, it is only necessary to use JavaScript to detect the size state of a picture in a timely state. The code is as follows: (but there is a premise is that this way is not what I think, nor I wrote the code, is the online friend summary of the code I just know there is such a principle)


var Imgready = (function () {
var list = [],
Intervalid = null;

Used to execute queues
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 picture is cached, the cached data is returned directly
if (img.complete) {
Ready.call (IMG);
Return
}
width = img.width;
Height = img.height;

Events after loading errors
Img.onerror = function () {
Error && Error.call (IMG);
Onready.end = true;
img = img.onload = Img.onerror = null;
};

Picture size Ready
var onready = function () {
Newwidth = Img.width;
Newheight = Img.height;
if (newwidth!== width newheight!== height
If the picture has been loaded elsewhere, the usable area can be detected
Newwidth * newheight > 1024
) {
Ready.call (IMG);
Onready.end = true;
};
};
Onready ();
Fully Loaded Events
Img.onload = function () {
OnLoad may be faster than Onready in the timer time difference range
Check here and ensure Onready priority
!onready.end && Onready ();
IE gif animation will loop to execute onload, empty onload can be
img = img.onload = Img.onerror = null;
};


To join a queue for periodic execution
if (!onready.end) {
List.push (Onready);
Reduces browser performance loss whenever only one timer is allowed
if (intervalid = = null) {
Intervalid = setinterval (queue, 40);
};
};
}
})();



The method is invoked as follows:

Imgready (' t2bde8xb0bxxxxxxxx-397746073.jpg ', function () {
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.