The past two decades the internet has taken enormous leaps in what we can do, and what users want to be able to do. The technologies involved in this have evolved just as rapidly. With the increasing available bandwidth we were able to push more data over the wire than we were used to, opening many doors. But this doesn’t mean we should no longer care about bandwidth and thus performance of our web applications.
Not only our applications have gotten larger, but our images as well. We want higher resolutions, and better looking images, but this also leads to larger file sizes and more resources. However, we often do not need to load all images all at the same time, but only when they enter (or about to enter) the viewport. This notion is not new, and we have done this already in the past by using, for example, jQuery Lazyload or other libraries that would handle this for us.
Earlier this year, there has been an update in the HTML specification, introducing the loading
attribute, which is the future of lazy loading your images without extra code or hassle. It’s easier than ever to lazy load your images and no longer an excuse to not do it. This is what it looks like and how to use it:
<img loading="lazy" src="https://picsum.photos/200/300" alt="My random image" />
The loading
attribute takes care of the loading strategy, and accepts three different values: auto
, lazy
, and eager
. Let’s quickly go over them and explain the behaviour:
auto
: default browser behaviour, and means the same as not including the attributelazy
: loads the image when the element is (almost) in the viewporteager
: loads the image immediately when the page is rendered
The tag is expected to be supported by all major browsers soon, but you can test it already in Firefox (version 75 or higher, set dom.image-lazy-loading.enabled
to true
) or in Chrome (version 76 or higher, set flag Enable lazy image loading
to true
).
I threw together a little Stackblitz, so you can see the attribute in action:
Who am I?
My name is Arjen Brandenburgh. I’m a senior frontend engineer and consultant working as Technical Lead for Techspire in the Netherlands. Working in the frontend field for almost 10 years and still loving it every single day. My main expertise lies with Angular. As a true geek I love to expand my knowledge and am proficient with Python, Ruby on Rails and AWS.
Do you think you have what it takes to work with us? At Techspire we’re looking for people who love technology as much as we do, and are looking to push themselves to expand their knowledge. Also, we love beer.