What is Lazy Loading in JavaScript: Explanation and Example
lazy loading is a technique where resources like images or code are loaded only when they are needed, not all at once. This helps improve page speed and user experience by delaying loading until the user actually needs the content.How It Works
Lazy loading works like waiting to open a book until you actually want to read it, instead of carrying all books at once. In web pages, instead of loading all images or scripts immediately, lazy loading waits until the user scrolls near them or triggers an action.
This saves time and data because the browser only downloads what is necessary at the moment. For example, images below the fold (not visible on screen) are loaded only when the user scrolls down to see them.
Example
This example shows lazy loading an image using the loading="lazy" attribute in HTML, which modern browsers support natively.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lazy Loading Example</title> </head> <body> <h1>Lazy Loading Image</h1> <p>Scroll down to load the image below.</p> <div style="height: 1000px; background: #eee;">Scroll down space</div> <img src="https://via.placeholder.com/600x400" loading="lazy" alt="Lazy loaded image"> </body> </html>
When to Use
Use lazy loading when your web page has many images, videos, or heavy scripts that slow down initial loading. It is especially helpful for long pages where users may not see all content immediately.
Examples include photo galleries, news sites, or e-commerce product lists. Lazy loading improves performance, reduces bandwidth use, and creates a smoother experience for users on slow connections or mobile devices.
Key Points
- Lazy loading delays loading resources until needed.
- It improves page speed and saves data.
- Modern browsers support lazy loading for images with
loading="lazy". - JavaScript can also implement lazy loading for scripts or other content.
- Best for pages with many images or heavy content.