Implementing WebP images in Jekyll
Adding WebP images to my Jekyll-based static site, brings it to new levels of optimization and performance.
What is WebP
WebP is a modern image format that provides superior lossless and lossy compression for images on the web. [ā¦] WebP lossless images are 26% smaller in size compared to PNGs. WebP lossy images are 25-34% smaller than comparable JPEG images at equivalent quality index. An image format for the Web, by Google
Implementation
I have three ways of adding images:
- through a
figure
module - through a responsive images module
- using a simple
img
tag
I just had to tweak the first two files under my _includes
folder and reach out for the few spare img
tags (mostly connected to my Indieweb integration).
Example: Figure module
Before
<figure class="{{ include.class | default: 'my-5 text-center' }}">
<img class="mx-auto" src="{{ include.image }}" alt="{{ include.alt | default: include.caption }}" {{ include.width ? include.width | prepend: 'width="' | append: '"' }} {{ include.height ? include.height | prepend: 'height="' | append: '"' }}>
{% if include.caption %}<figcaption class="p-name mt-3 caption">{{ include.caption }}</figcaption>{% endif -%}
</figure>
After
I created a picture
element containing all the srcset
needed for a full support. Although WebP is supported on all major browsers, Iām serving fallbacks to older versions.
<figure class="{{ include.class | default: 'my-5 text-center' }}">
<picture>
<source srcset="{{ include.image | replace:'.png','.webp' | replace:'.jpg','.webp' | replace:'.jpeg','.webp' }}" type="image/webp">
<source srcset="{{ include.image }}" {% if include.image contains '.jpg' or include.image contains '.jpeg' %}type="image/jpeg"{% elsif include.image contains '.png' %}type="image/png"{% endif %}>
<img class="mx-auto" src="{{ include.image }}" alt="{{ include.alt | default: include.caption }}" {{ include.width ? include.width | prepend: 'width="' | append: '"' }} {{ include.height ? include.height | prepend: 'height="' | append: '"' }}>
</picture>
{% if include.caption %}<figcaption class="p-name mt-3 caption">{{ include.caption }}</figcaption>{% endif -%}
</figure>
Results
I got a double 100%
on GTMetrix, and improved my 512k club rank. I cut the loading time by a considerable amount in pages with multiple images. Iām now serving responsive images where needed, in WebP format where supported.
Reply via email or use webmentions