PageSpeed, WordPress Tips

Serving appropriately-sized images can save many bytes of data and improve the performance of your webpage, especially on low-powered devices.

The GTmetrix result before images optimization:

Before scaled images

The GTmetrix result after images optimization:

After scaled images

To achieve this result I’ve used the image srcset and sizes attributes.

srcset="img-300x200.png 300w, img-600x400.png 600w, img-1200x800.png 1200w"

srcset is a set of sources where the browser can find the desired image at different sizes. In addition to the URL for the image, the image’s width is also included in the srcset.
For example, if someone hits your site from a 320px wide iPhone, their browser won’t have to download a 2400px image. In this way your site will be faster.

The sizes attribute is mandatory but is useful to tell the browser the width of an image at various breakpoints.

sizes ="(media query) width, (media query) width, fallback width"
sizes="(max-width: 768px) 50vw, (max-width: 992px) 690px, 910px"

The above code means “when my viewport is less than 768px wide, my image takes up 50% of the screen. When my viewport is greater than 768px but less than 992px wide, my image is 690px wide. Otherwise, my image is 910px wide”.

The final code is:

<img src="img.png" alt="My Image" srcset="img-300x200.png 300w, img-600x400.png 600w, img-1200x800.png 1200w" sizes="(max-width: 768px) 50vw, (max-width: 992px) 690px, 910px">

In WordPress you have to open your theme’s functions.php file and add new image sizes:

add_action('init', 'add_image_sizes');
function add_image_sizes() {
	add_image_size( '540wide', 540 );
	add_image_size( '440wide', 440 ); 
	add_image_size( '690wide', 690 ); 

}

Then, in your custom template file add:

<img src="<?php the_post_thumbnail_url(); ?>" alt="<?php the_title(); ?>" srcset="<?php the_post_thumbnail_url('440wide');?> 440w, <?php the_post_thumbnail_url('540wide');?> 540w, <?php the_post_thumbnail_url('690wide');?> 690w" sizes="(max-width: 768px) 50vw, (max-width: 992px) 690px, 100vw">