How to use WebP images effectively

brettanda

Brett Anda 🔥🧠

Posted on January 28, 2020

How to use WebP images effectively

WebP images are great for everyone because they have many things going for them. They are new(ish) to the web which means they aren't accepted everywhere (yet). Two of the best things about them are that they compress like JPG images to very small file sizes, and they support transparency like PNG images.

The picture element

When adding these to your website you can just put them in an image tag and be done. Doing so will leave out older browsers and/or devices that just don't support Webp images yet.

<img src="/file/path/to/image.webp" alt="Some bacon webp image" />
Enter fullscreen mode Exit fullscreen mode

Backup images

While this does work for browsers that support the Webp file type the image won't display on browsers that don't support the file. The best way to add Webp images to your site would be a <picture> element. The way the picture element works is by loading the first file type that can be loaded by the browser. Within the picture element, you will need <source> elements. The source elements are where you add the src attribute to the different file types. The first source element in the parent picture element is the first to be loaded if the file type is supported. The first source element is where you want to put the source for the Webp file that you want to add. You will also want to add a type attribute to tell the browser what file type the file is.

<picture>
    <source type="image/webp" src="/file/path/to/image.webp" />
    <source type="image/png" src="/file/path/to/image.png" />
</picture>
Enter fullscreen mode Exit fullscreen mode

Un-supported picture tag

Adding the above to your website won't work just yet because the picture element requires a backup img within the picture element. This is for browsers that don't support the picture element yet. This img element is also where you will add all your SEO related attributes, include the alt attribute.

<picture>
    <source type="image/webp" src="/file/path/to/image.webp" />
    <source type="image/png" src="/file/path/to/image.png" />
    <img src="/file/path/to/image.png" alt="This images contains bacon" />
</picture>
Enter fullscreen mode Exit fullscreen mode

For the img element added in the picture element should not be a webp image because if the browser is too old for the picture element then it is also too old for loading Webp images.

💖 💪 🙅 🚩
brettanda
Brett Anda 🔥🧠

Posted on January 28, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related