One, lazy loading
1. What is lazy loading
Lazy loading, also known as lazy loading, refers to the lazy loading of images on long web pages and is a great way to optimize web page performance.
2. Why lazy loading
- Improves user experience, but takes a long time to wait, which seriously affects user experience.
- Reduce the load of invalid resources, which significantly reduces the strain and traffic on the server, as well as the browser load.
- Prevent the concurrent loading of too many resources will block js loading, affecting the normal use of the website.
3. Lazy loading principle
First, set the SRC attribute of the image on the page to an empty string, and the real path of the image is set in the data-original attribute. When the page is scrolling, it needs to listen for the Scroll event. In the callback of the Scroll event, If the SRC attribute of the image in the viewable area is set to the value of data-original, then lazy loading can be realized.
<html lang="en"> <head> <meta charset="UTF-8"> <title>Lazyload</title> <style> .image-item { display: block; margin-bottom: 50px; height: 200px; </style> </head> <body> <img SRC ="" class="image-item" lazyload="true" data-original="images/1.png"/> <img src="" class="image-item" lazyload="true" data-original="images/2.png"/> <script> var viewHeight = document. DocumentElement. ClientHeight / / for visual zone height function the lazyload () {var Eles = document. QuerySelectorAll (' img [data - the original] [the lazyload] ') Array. The prototype. The forEach. Call (eles, function (item, index) { Var the rect if (item. The dataset. What = = = "") return the rect = item. GetBoundingClientRect () / / used to obtain an element in the page, left, If (rect.bottom>=0 &&rect. top < viewHeight){! function(){ var img=new Image() img.src=item.dataset.original img.onload=function(){ item.src=img.src } Item.removeattribute ("data-original")// Remove the attribute, and the next time you don't iterate through item.removeAttribute (" lazyLoad ")}()}})} lazyLoad () Want to trigger a function first, initialize the page page picture document. The addEventListener (" scroll ", the lazyload) < / script > < / body > < / HTML >Copy the code
Two, preloading
1. What is preloading
All required resources are requested to be loaded locally in advance so that they can be accessed directly from the cache later when they are needed.
2. Why preload
Load some of the main content before the web page is fully loaded to provide a better user experience and reduce waiting time.
Three, contrast
Lazy loading relieves pressure on the front end of the server, while preloading increases pressure on the front end of the server.