Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Itsopensource profile imageTrishul
Trishul forItsopensource

Posted on • Edited on • Originally published atitsopensource.com

     

Lazyload images the browser way

One of the biggest performance wins for image-extensive webpages islazy loading. Normally, the browser fetches all the required resources from the server as soon as possible. When the website has lots of images this goes against the speed and performance of the website. Consider a page loading 100s ofdog images, there will be 100 asynchronous http requests. The more the http requests, the slower the website.

All images are required for the functionality of the website, but they might NOT be required on the FIRST load. HereLazy loading does the magic— images will be fetched only when they are required for the content in the current view port. So for a long image-extensive page, the images which are required by the top part of a website will be initially fetched on the first load and as the website is scrolled down, the respective images are fetched.

This has been practiced for a while and various Javascript libraries are built to achieve this.

The list goes on. But the good news is the specification for native image lazyloading has been merged into the HTML standards. CheckHTML standard repo.

Official specs -https://html.spec.whatwg.org/multipage/urls-and-fetching.html#lazy-loading-attributes

With this we don't need any lazy loading libraries anymore and all we need to do is the following:

<imgloading="lazy"src="https://placedog.net/400/400/random"alt="doggo">
Enter fullscreen modeExit fullscreen mode

Notice theloading attribute, this is the magic keyword. It accepts 3 valuesauto,lazy,eager

  • auto - this is equivalent to not including theloading attribute. This sets the default browser behavior for images.
  • lazy - fetches images only when the element is in/near the viewport.
  • eager - fetches the images immediately.

Lazyload will soon be supported in all major browsers by default. But if you want to test it, you can turn on the browser's experimental flags:

Firefox (>=75):

  1. Gotoabout:config
  2. Setdom.image-lazy-loading.enabled totrue

Chrome (>=76):

  1. Gotochrome://flags
  2. SetEnable lazy image loading toEnabled

Demo:https://itsopensource.com/demos/lazyload/

Lazyload in action

Lazyload in action

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

More fromItsopensource

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp