How to Lazy Load Images in a Web Page

Major browsers, Chrome, Firefox, Opera, support lazy loading for image in HTML img tag by default, no JavaScript code needed.

Lazy Load Image in HTML with loading Attribute in img

<img src="image-url" loading="lazy" />

Backward compatibility

loading attribute cause no error for older versions of supporting browsers or those which do not support as browsers ignore unknown attributes including loading attributes.

lazy loading supporting browser

Browsers based on Chromium engine support lazy loading e.g. Chrome, Opera, Edge as well as Firefox. Safari will support loading attribute soon.

loading options

There are three options of loading attribute in img tag:

lazy

<img loading="lazy" /> loads images in img when the user view is near to or on to the img tag.

eager

<img loading="eager" /> loads images even the user viewport not reached, which is the default behavior. Same as loading attribute not included in the img tag.

loading="lazy" example

Following IS the example of loading lazy, first open Console of the Browser (use F12 as shortcut key). Monitor the console log of the browser to experience the effect. Do Change the src with a valid image url first:

<html>
<head>
</head>
<body>
<p style="padding:300vh 0 0 0;display:inline-block"></p>
<img src="your-image-url" style="height:50px;width:50px" loading="lazy" onload="console.log('lazy',new Date())"/>
</body>
</html>

loading="eager" example

<html>
<head>
</head>
<body>
<p style="padding:300vh 0 0 0;display:inline-block"></p>
<img src="your-image-url" style="height:50px;width:50px" loading="eager" onload="console.log('eager',new Date())"/>
</body>
</html>
Posted Article in Programming
Login InOR Register