Parsing JavaScript pictures lazy loading and preloading analysis and summarization _javascript skills

Source: Internet
Author: User
Tags setinterval browser cache

This article mainly introduces lazy loading and preload two technology analysis, nonsense not to say, together to see.

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 essence 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 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);
  }
}

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 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 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, Newhei
    Ght, img = new Image ();

    img.src = URL;
      If the picture is cached, it returns the cached data directly if (Img.complete) {Ready.call (IMG);
    Return
    } width = img.width;

    Height = img.height;
      Event Img.onerror = function () {Error && Error.call (IMG) After loading error
      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 to detect newwidth * newheight > 1024) {ready.call (IMG);
      Onready.end = true;
    };
    };
    Onready (); Fully Loaded event Img.onload = function () {//onload may be inspected in the timer time difference than onready fast//here and ensure that Onready priority is enforced!onre
      Ady.end && Onready ();
    IE gif animation will loop to execute onload, empty onload can be img = img.onload = Img.onerror = null;
    
    
    };
      Join the queue to execute the IF (!onready.end) {List.push (onready) periodically;
      Reduces browser performance loss whenever only one timer is allowed (intervalid = = null) {Intervalid = setinterval (queue, 40);
    };
  };

 }
})();

The method is invoked as follows:

Imgready (' yun_qi_img/t2bde8xb0bxxxxxxxx-397746073.jpg ', function () {
alert (' width: ' + this.width + ' height: ' + this.height);
};

The above is the entire content of this article, I hope this article will help you, I hope you continue to pay attention to our website! Want to learn JSP can continue to focus on this site.

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.