Loading Attribute in HTML: What It Is and How to Use It
loading attribute in HTML tells the browser when to load images or iframes, either immediately or lazily. It helps improve page speed by delaying loading of off-screen content until needed.How It Works
The loading attribute controls when the browser loads images or iframes on a webpage. Normally, browsers load all images and iframes as soon as the page starts loading, which can slow down the page if there are many or large files.
Using loading="lazy" tells the browser to wait and only load these resources when they are about to scroll into view. Think of it like waiting to open a book until you actually reach that chapter, instead of opening all chapters at once.
This helps save data and speeds up the initial page display, especially on slower connections or devices.
Example
This example shows an image with the loading="lazy" attribute. The image will load only when you scroll near it.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Loading Attribute Example</title> <style> body { height: 1500px; margin: 0; padding: 20px; font-family: sans-serif; } img { display: block; margin: 1000px auto 0; max-width: 100%; height: auto; } </style> </head> <body> <h1>Scroll down to load the image</h1> <img src="https://via.placeholder.com/600x400" alt="Example Image" loading="lazy"> </body> </html>
When to Use
Use the loading attribute to improve page speed and user experience by delaying loading of images or iframes that are not immediately visible. This is especially helpful for pages with many images or embedded content.
Common use cases include long articles with many pictures, image galleries, or pages with embedded videos or maps that appear below the fold (off-screen initially).
Note that loading="lazy" is supported in most modern browsers, but you should test your site to ensure compatibility.
Key Points
- The
loadingattribute can be set tolazyoreager. lazydelays loading until the element is near the viewport.eagerloads the element immediately (default behavior).- Improves page load speed and reduces data usage.
- Works on
<img>and<iframe>elements.