Home >Web Front-end >JS Tutorial >Implementation methods and ideas for delayed loading of js images_javascript skills
The approximate implementation method is:
Before the load of the page is triggered, put all the img in the element with the specified ID into imgs, and put the src value of all the pictures into a newly created _src attribute. , set src to the specified display image.
Then, when the scroll event of document.body is triggered, the loop calculates whether the position of the img element in imgs is exactly within the browser display box. If so, the value of the _src attribute of the img element is assigned to src. This way the picture will be displayed.
The more troublesome part here is how to calculate the position of img and obtain the absolute position of the element relative to the page. OffsetLeft and offsetTop are usually used, but these two attributes are the relative position of the element pointed to by the element's offsetParent. If the element pointed by offsetParent is set to float or uses absolute positioning, then offsetLeft is incorrect to obtain the absolute position.
Here I use the sum of the offsetTop of all parent elements of the element to obtain the absolute position of the document.