What is lazy loadingLazy loading is actually lazy loading, which is a way to optimize the performance of web pages. For example, when visiting a page, the images in the visual area should be displayed first instead of loading all the images at one time, and the image request should be sent when the display is needed to avoid loading too many resources when opening the web page.
When to use lazy loading
Lazy loading is often the case when a page needs to load many images at once.
Lazy loading principleWe all know that the <img> tag in HTML represents an image in a document. Said nonsense..
The <img> tag has an attribute called SRC, which represents the URL of the image. When the value of this attribute is not empty, the browser sends a request based on this value. If there is no SRC attribute, the request will not be sent.
Huh? Looks like we can use that to our advantage?
I’m not going to set SRC until I need to set SRC, okay?
Nice, that’s it.
Instead of setting SRC for <img>, put the actual URL of the image in another attribute, data-src. When needed, before the image is visible, pull the URL out and put it in SRC.
implementation————————————————————————————————
HTML structureIf you look closely, the <img> tag now has no SRC attributes, only Alt and data-src attributes.
The Alt attribute is a required attribute that specifies alternative text in case the image cannot be displayed. Data -* Global properties: Properties that make up a class of properties named custom data properties and can be accessed through htmlElement.dataset.
How do I determine if an element is in the viewable areaMethods a
I’ve seen a lot of this online, so take notes.
- Through the document. The documentElement. ClientHeight obtain visual window screen height
- Through the document. The documentElement. ScrollTop access at the top of the browser window with a document at the top of the distance between, also is the scroll bar rolling distance
- Get the distance of the element from the top of the document with element.offsetTop
Then check whether ②-③<① is true, if true, the element is in the visible area. Method two (recommended) uses the getBoundingClientRect() method to get the size and position of the element, as described in the MDN: The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport. This method returns a DOMRect object named ClientRect that contains the values top, right, Botton, left, width, and height. MDN has this picture:
You can see that the element position returned is relative to the upper-left corner, not the margin.
Let’s think about when the picture goes into the viewable area.
Suppose constbound = el. GetBoundingClientRect (); To represent the distance from the picture to the top of the visible area; And set constclientHeight = window. InnerHeight; To indicate the height of the visible area.
As we scroll down the bound.top, the distance between the image and the top of the viewable area gets smaller and smaller. When bound.top===clientHeight, the top edge of the image should be at the bottom of the viewable area.
That is, when bound.top<=clientHeight, the image is in the viewable area.
Here’s how we judge:
We have a plus 100 here for preloading.
Loading picturesWhen the page opens, all images need to be checked to see if they are in the viewable area and loaded if so.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
|
function checkImgs() {
const imgs = document.querySelectorAll( '.my-photo' );
Array.from(imgs).forEach(el => {
if (isInSight(el)) {
loadImg(el);
}
})
}
function loadImg(el) {
if (! el.src) {
const source = el.dataset.src;
el.src = source;
}
}
|
There should be an optimization here, set an identifier to identify the index of the loaded image, when the scroll bar is scrolling, it does not need to go through all the images, only need to go through the images that are not loaded. Function throttling refers to “function throttling, function shaking” in frequent DOM operations such as scrollbar scrolling. The so-called function throttling is to make a function not execute too often and reduce the number of fast calls to throttling. Basic steps:
- Gets the timestamp of the first triggered event
- Gets the timestamp of the second triggered event
- If the time difference is greater than a certain threshold, the event is executed and the first time is reset
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
|
function throttle(fn, mustRun = 500) {
const timer = null ;
let previous = null ;
return function () {
const now = new Date();
const context = this ;
const args = arguments;
if (! previous){
previous = now;
}
const remaining = now - previous;
if (mustRun && remaining >= mustRun) {
fn.apply(context, args);
previous = now;
}
}
}
|
MustRun is the interval between calls to the function. However frequently the fn is called, it can only be executed if remaining>=mustRun. Experiment — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — page is opened
You can see that only img1 and img2 have been loaded. No other IMG requests have been sent
The first image is rendered in its entirety, but the second image is not visible as soon as it enters the viewable area
When the page scrolls
Now the second image is fully visible, and the third image is slightly visible, and we look at the request
The imG3 request is sent, but the subsequent request is still not sent
Full load timeWhen the scroll bar rolls to the bottom, all requests should be made, as shown
The article is reproduced at: https://juejin.cn/post/1