Analysis of lazy loading and preload of JavaScript pictures

Source: Internet
Author: User
Tags http request setinterval browser cache

The basic concepts of

  lazy loading and preload.

  Lazy loading is also called delay loading: The previous article has introduced: JS pictures delay loading pictures or certain conditions to load some pictures.       preload: Loading pictures in advance, rendering them directly from the local cache when they need to be viewed.     The nature of two technologies: the behavior of the two is the opposite, one is to load in advance, one is slow or even does not load. 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 load and implementation of the significance of:       Significance: lazy load is the main purpose of the server as a front-end optimization, reduce the number of requests or delay requests.       Implementation:          1. The first is a purely deferred load, with settimeout or setinterval loading latency.       2. The second is conditional loading, which meets certain conditions, or triggers some events to begin an asynchronous download.       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 of the scroll bar to achieve, will generally be seen from the user to see a certain distance before the beginning of the load, so that users can be sure to pull down when the picture     Pre-loading and implementation of the significance of:       preload can be said to be sacrificing the front-end performance of the server, in exchange for a better user experience, so that users can be the fastest response to the operation. There are many ways to implement preload, you can use CSS (background), JS (Image), HTML (<img/>). 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 I implement preload?   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 = NE W Image (); &nbsp        IMG.SRC = URL;     Img.onload = function () {        img.onload = null;         Callback . Call (IMG);    }   testing is normal in Google or Firefox, no matter how I refresh it is normal, but it is not the case under 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, is the browser cache, 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 looks like this:   function LoadImage (url,callback) {    var img = new Image ();        &N Bsp img.src = URL;       if (img.complete) { //If the picture already exists in the browser cache, direct call callback function              & nbsp   Callback.calL (IMG);         return; Direct return without processing onload events    }       img.onload = function () {        Img.onload = NULL;         Callback.call (IMG);    } to copy code that is, if the picture 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 code above: you have to wait for the picture to be loaded, you can perform the callback function, or we can get the width and height of the picture when the picture is loaded. 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 queue     var queue = function () {          for (var i = 0; I & Lt List.length; i++) {            List[i].end list.splice (i--, 1): List[i] ()         }        !list.length &&Amp Stop ();    };         /Stop all timer queues     var stop = function () {        Clearinter Val (intervalid);         intervalid = null;     {    return function (URL, ready, error) {        var onready = {},  &nb Sp           width,              height,      &NBS P       newwidth,              Newheight,         &NBS P   img = new Image ();         IMG.SRC = URL;          //If the picture is cached, direct return cached data         if (img.complete) {    &NBSP ;       Ready.call (IMG);             return;        }         width = img.width;         height = img.height; &nBsp        //Loading Error event           Img.onerror = function () {            Error && Error.call (IMG);             Onready.end = true;             img = img.onload = Img.onerror = null;        };          //Picture size ready         var onready = function () {      & nbsp     newwidth = img.width;             newheight = img.height;             if (newwidth!== width | | newheight!== Height | |         &N Bsp      //If the picture has been loaded in another place can be used to detect               Newwidth * newheight > 1024            ) {                Ready.call (IMG);                Onready.end = true;            };        };         Onready ();        //Fully loaded event         img.onload = function () {      &NBSP ;    /onload in the timer time range may be more than Onready fast            //here to check and ensure that Onready priority implementation of the   &NBS P        !onready.end && onready ();            //IE gif animation will loop to execute onload, empty onload can be             img = Img.onload = Img.onerror = null;        };                          //Join queue periodically execute         if (!onready.end) {            List.push (Onready);       &NBS P    /Whenever only one timer is allowed to appear, reduce browser performance loss             if (IntervaliD = = null) {                Intervalid = setinterval (queue,);     & nbsp      };        };    }}) (); The invocation mode is as follows:   Imgready (' t2bde8xb0bxxxxxxxx-397746073.jpg ', function () {alert (' width: ' + this.width + ' height: ' + this.h eight); });

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.