Hi everyone, this is a quick tutorial on how to deliver fast images using Modx. Many times, I asked for help on the forums, and so I thought it would be nice if I could help others too.
Before we begin: If you are reading this from the future, Avif format has probably taken over the web. At the time I am writing this tutorial, Safari is not supporting Avif images yet, so it doesn’t make much sense to use it right now. But if you want to use Avif instead of WebP, the implementation should be the same. Also bear in mind that you would probably need to use at least php 8.1 to do so, as this is the first version of php providing support for Avif images.
Also note: I am using phpthumbon, but if use another version of this plugin ( phpthumbof for eg. ), the principle remains the same.
Alright, let’s get started.
You are probably reading this because you tested your website speed on google page speed, and google is not very happy that you are using jpeg and png to display your images.
You have two options:
- Converting your images one by one ( please don’t do that ) using a software such as photoshop and the appropriate google extension
- Use the power of Modx and let your CMS/F do the hard work for you.
So first, this is how an image is normally displayed on the web:
<img src="path/to/image/150.jpg" width="150" height="150" alt>
Because there are still many browsers that don’t support WebP ( Safari for systems prior to Big Sur, internet explorer … ), we can’t directly replace our jpg image to a WebP format, as it will not be displayed for everyone.
This is what we will be using:
<picture>
<source srcset="path/to/image/150.webp" type="image/webp">
<source srcset="path/to/image/150.jpg" type="image/jpeg">
<img src="path/to/image/150.jpg" width="150" height="150" alt>
</picture>
What this does is really simple:
- Your system support WebP => your browser displays the WebP image.
- Your system does not support WebP => you see the jpeg version
Now it is the part where phpthumbon comes into action: we want the plugin to convert our image to WebP .
1 - First step: Install the plugin ( crazy right ?! Who knew? )
2 - Second step: If you are going to call the image directly into you template or page, you will use to code below:
<picture>
<source srcset="[[phpthumbon? &input=`path/to/image/150.jpg` &options=`f=webP`]]" type="image/webp">
<source srcset="[[phpthumbon? &input=`path/to/image/150.jpg`]]" type="image/jpeg">
<img src="path/to/image/150.jpg" width="150" height="150" alt>
</picture>
Well, that’s it! Easy peasy!
Now your images are lightning fast!
Of course, there are alternate options available if you use a TV instead of direct image path, but you’ll find more info in each plugin’s documentation. (Feel free to post your tips and tricks below, it could help others).
But you get the idea!
References: