This article mainly introduces how native javaScript achieves delayed image loading without loading the jQuery script. it is a very practical technique, for more information about how to implement image loading with native javaScript, see the following example. In fact, the jquery plug-in is available for image delayed loading, and the loading method is very simple and reasonable. However, some friends thought that loading the jquery plug-in package was too large, and they wrote one at a time, to share with you.
First, delayed image loading can save our bandwidth and improve user experience, especially for sites with multiple images, the following describes the principle and implementation code of a piece of delayed loading.
Principle of delayed image loading
The principle of delayed image loading is that the image src in html is not the real image address, but the image address is assigned to the img label with a custom attribute, for example: src = "img/loading.gif" data-url = "img/1.jpg", and then judge the browser scroll bar event through js, when the image reaches a certain point, the real address of the image in the custom attribute is assigned to the src of the current img label to achieve dynamic display of the image. In real projects, the addresses of these images can be passed through ajax and assigned to the custom attributes of img.
Native JS implements Image delayed loading instances:
The text seems boring after all. I wrote a simple demo and now I have pasted all the code. if you need it, you can copy it directly and check the code to understand it.
The code is as follows:
Delayed image loading