How to implement delayed loading of non-first-screen images in JS
Below I will share with you an example of using JS to implement delayed loading of non-first-screen images. It has a good reference value and I hope it will be helpful to everyone.
Goal
Reducing resource loading can significantly optimize the page loading speed, so it can reduce the number of images that are downloaded immediately when the page loads. , to improve the page loading speed, and other images will be loaded when needed.
Thoughts
If you want to achieve the above goals, there are several things you need to think about.
1. How to determine which images need to be loaded immediately and which ones can be loaded later?
2. How to control images to be loaded at a specified time?
Regarding the first question, the pictures that will be seen by the user when the page is opened must be loaded immediately, and the others can be delayed. That is, the image in the window needs to be loaded immediately. So how to determine whether the picture is in the window? getBoundingClientRect can return the size of the element and its position relative to the viewport (detailed description)
You can determine whether the image is in the viewport through the values of top and right in the image.
For the second question, do not specify src for img first. Instead, store the image link address in the src attribute (customized) of the element. When it needs to be loaded, assign it to src before starting the download. picture.
Implementation
Now that we have the idea, we start to implement it. Use the following HTML to test
<p class="container"> <h1 id="图片懒加载">图片懒加载</h1> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <img class="lazy-img lazy" src="/static/imghwm/default1.png" data-src="" alt=" alt="" > <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <img class="lazy-img lazy" src="/static/imghwm/default1.png" data-src="" alt=" alt="" > <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <img class="lazy-img lazy" src="/static/imghwm/default1.png" data-src="" alt=" alt="" > <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <img class="lazy-img lazy" src="/static/imghwm/default1.png" data-src="" alt=" alt="" > <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <img class="lazy-img lazy" src="/static/imghwm/default1.png" data-src="" alt=" alt="" > <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> <p>测试性配文,测试图片懒加载</p> </p>
The links in the html are all from Baidu images. You can check whether they are loaded in the network. The style is ignored here. According to the previous idea, there is the following code
//所有的图片 var imgs = document.querySelectorAll('.lazy-img'); //首屏图片加载 lazyLoad(imgs) //剩余图片加载---监听滚动事件 window.addEventListener('scroll',function(){ //滚动事件触发太频繁了,所以加上节流 throttle(lazyLoad(imgs),200,500) }) }
The following is how to implement lazyLoad
function lazyLoad(imgs,offset){ offset = offset || 100; if (!imgs || imgs.length < 1) { console.log('imgs为空'); return ; } [].slice.call(imgs).forEach(function(element,index){ //元素的DomRect var rect = element.getBoundingClientRect() //出现在视窗中 if (rect.top <= window.innerHeight + offset && rect.right > 0) { element.setAttribute('src',element.getAttribute('src')) } }) }
Get the height of the window through window.innerHeight. When the distance between the element and the upper edge of the window is At offset, load the image; where offset is the specified offset distance.
The throttling function is as follows
function throttle (fn, delay, atleast) { let timer = null let startTime = new Date() return function () { let context = this let args = arguments let curTime = new Date() clearTimeout(timer) if (curTime - startTime >= atleast) { fn.apply(context, args) // apply 指定函数指向的 上下文(this) 和 参数列表 startTime = curTime } else { timer = setTimeout(function () { fn.apply(context, args) startTime = curTime }, delay) } } }
Effect
The page is loaded, only loaded A picture
Scroll down to the specified position, and then the subsequent pictures will be loaded in sequence
The above JS The example of implementing delayed loading of non-first-screen images is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to implement collision detection in JS
##How to manage header tags using vue-meta
How to modify the a tag style in vue?
What are the 7 practical tips about ES6?
The above is the detailed content of How to implement delayed loading of non-first-screen images in JS. For more information, please follow other related articles on the PHP Chinese website!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1
Easy-to-use and free code editor
