Preloaded and lazy loading

This article was originally Links: https://www.cnblogs.com/yaoyao-sun/p/10367193.html

Pictures lazy loading and preloading

 


Preloading

1.1 What is pre-loaded?
Load picture is pre-loaded in advance, when you need to view can be rendered directly from the local cache. Why use preload?

1.2 When page images relatively large, when the page loads will appear blank area or see the effect of the picture is loaded slowly out, in order to improve the user experience, the need to
take these pictures loaded into the cache ahead of time, when the user open a page, these images will quickly revealed, a better user experience.

1, is loaded in the CSS background: increase the overall page load time

#preload-01 { background: url(-01.png) no-repeat -9999px -9999px; }
#preload-02 { background: url(-02.png) no-repeat -9999px -9999px; }

Method 2, JS new image object, setting the src Load: commonly used is the new Image () ;, set its src to implement pre-loaded, and then use onload callback method preload completion event.

Copy the code
function preloader() {
    if (document.images) {
        var img1 = new Image();
        var img2 = new Image();
        var img3 = new Image();
        img1.src = ";;
        img2.src = ";;
        img3.src = ";;
    }
}
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {//onload中未挂载函数才执行该JS
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}
addLoadEvent (the preloader); 
div.appendChild (IMG1); // inserted into the DOM
Copy the code

Method 3, Ajax preload, new Image () object is set src

Copy the code
window.onload = function() {
    setTimeout(function() {
        // XHR to request a JS and a CSS
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url;);
        xhr.send();
        xhr = new XMLHttpRequest();
        xhr.open('GET', url;);
        xhr.send();
        // preload image
        new Image().src = ";;
    }, 1000);
};
Copy the code
 
Commonly used are new Image () ;, set its src to implement pre-loaded, and then use onload callback method preload completion event.
Copy the code
loadImage function (url, callback) 
{ 
  var img = new new Image (); // create an Image object to achieve the pre-downloaded pictures 
  img.src = url; 
  IF (img.complete) 
  {// If the image is already in the browser caching, direct callback function 
    callback.call (img); 
    return; // return directly, do not have to deal with the onload event 
  } 
  img.onload = function () 
  {// Photo Download asynchronous call callback function when completed. 
    callback.call (img); // callback function will replace this Image object, if you just use img.width when the picture has not been fully downloaded 
  }; 
}
Copy the code

  

Test Case:
function imgLoaded()
{
  alert(this.width);
}
<input type="button" value="loadImage" onclick="loadImage('aaa.jpg',imgLoaded)"/>
When the image is loaded once in the future, if there is another request for the picture, because the browser cache already lived this picture, and will not launch a new request, but come loaded directly from the cache. For firefox and safari, they view the two loading transparent to the user, it will also cause the onload event of the picture, but ie and opera ignore this identity, does not cause the image onload event
 
Or by using the img tag background-image property tags can be achieved preloaded pictures. However, in order to avoid excessive initial load images affect experience. After the document is generally best to render complete reload (using window.onload, etc.).
 
Scenes:
If one of the results need to replace the background picture, the picture will temporarily go to load, it will take a while to appear picture is displayed, the user experience will deteriorate, so the picture needs to pre-load. For example, photo wall, rolling picture of what needs to seamlessly display images, it is not a good photo before loading the next image to be displayed when the temporary lead to pull the picture display pictures too slow.
 
 

Lazy loading

2.1 What is lazy loading?
Lazy loading, also known as lazy loading. When visiting a page when you need to first background image img elements or other elements of the first with a picture instead of the default (placeholder chart), like this

Browser page rendering time on request only once. When the picture appears in the viewable area of ​​the browser, just set the true path of the picture, the picture is displayed.

2.2 Why use picture lazy loading?
When the number of pages in a multi-picture to a certain amount of time, and the picture size is relatively large, such as various shopping sites, network, etc. picture material. If you load a page at the time of
loading all the pictures will obviously affect the site loading speed and increase the burden on the server, and the user experience is not inevitable, then it may be time to employ lazy loading.

2.3 lazy loading concrete realization of the principle
reasons why the page img element sends http request is to set the src attribute, otherwise the browser will not send the request to download this image. First of all in the page

FIG images with a placeholder placeholder performed, and sets data-src custom property in the element, the true path stored images when taking out the need to use movable true path

State added to the src.

Meaning: The main purpose of lazy loading is optimized as a front-end server, server front end to ease pressure, reduce the number of one-time request or delay request.
 
Method to realize:
 
    1. The first is pure lazy loading, or use setTimeOut setInterval loading delay.
 
    2. The second condition is loaded, subject to certain conditions, or trigger a certain event began asynchronous download.
 
    3. The third area is a visual load, load only area that is visible to the user, this is mainly implemented by monitoring the scroll bar, usually see a picture before a certain distance away from the user to start loading times, this will ensure that users just to see the picture down.
 
Pictures did not pull the trigger back will onerror event
 

Lazy loading: the image src assigned to a default picture, when the user scrolls the scroll bar to the visible area of ​​the picture when loaded again the real picture

Copy the code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Lazyload 2</title>
    <style>
    img {
        display: block;
        margin-bottom: 50px;
        height: 200px;
    }
    </style>
</head>
<body>
    <img src="images/loading.gif" data-src="images/1.png">
    <img src="images/loading.gif" data-src="images/2.png">
    <img src="images/loading.gif" data-src="images/3.png">
    <img src="images/loading.gif" data-src="images/4.png">
    <img src="images/loading.gif" data-src="images/5.png">
    <img src="images/loading.gif" data-src="images/6.png">
    <IMG the src = "Images / loading.gif" Data-the src = "Images / 7.png">
        if(curTime - startTime >= atleast) {
            startTime = curTime; 
        } else {
= the setTimeout timeout (Fn, Delay); } } } function lazyload () { var = Images document.getElementsByTagName ( 'IMG'); var len = images.length; var n-= 0; // to store pictures loaded position, avoid traversing each time the first picture from the return function () { var seeHeight = document.documentElement.clientHeight; var = document.documentElement.scrollTop scrollTop || document.body.scrollTop; for (I = n-var; I < len; I ++) { IF (Images [I] .offsetTop <seeHeight scrollTop +) { IF (Images [I] .getAttribute ( 'the src') === 'Images / loading.gif') { Images [I] = .src Images [I] .getAttribute ( 'the src-Data'); } n-n-+ =. 1; } } } } var LoadImages lazyload = (); LoadImages (); // initialize the home page image window.addEventListener ( 'Scroll', throttle (LoadImages, 500, 1000), to false);
  // function of throttle (throttle) and debounce function (debounce) process,
// delay, and the interval of 500ms to 1000ms, when exceeds 1000ms this function is not triggered, the function is executed immediately, or delay the execution of the function 500ms </ Script> </ body> </ HTML>
Copy the code
 
 

Scenarios recommended links

Reproduced in: https: //www.cnblogs.com/leftJS/p/11079585.html

Guess you like

Origin blog.csdn.net/weixin_34161083/article/details/93722622