How to fix Properly Images size Pagespeed error on WordPress

There are too many themes around and many of them doesn’t set rightly image sizes or for some reasons you don’t have the right one.

On Google PageSpeed you can get the error “Properly Images Sizes” that is not easy to understand because doesn’t says what is wrong.

If you are using WordPress since more then an year all the image printed in page have an attribute srcset that let’s the browser to pick the right image size based on the user browser resolution.

The problem is that you can’t see what is the image path used in the browser as the HTML doesn’t change in DOM as the path is set on an internal parameter currentSrc so to get the actual path you need:

  • In Chrome developer tools inspect the element, then click the properties tab.
  • In Firefox developer tools inspect the element, right click and select DOM from the context menu.

The next step is using this very useful JS script that you can add on your bookmark.

https://ausi.github.io/respimagelint/

Next open the page with the issue and run that.

You will get a modal in the page that include an analysis for all the images suggesting how to change the srcset parameter.
The last step is to get this PHP snippet to insert in your theme to customize for your need:

add_filter(
    'wp_calculate_image_sizes',
    function( $sizes ) {
        if ( $sizes == '(max-width: 1200px) 100vw, 1200px' ) {
            $sizes = '(min-width: 1320px) 972px, (min-width: 1040px) 756px, (min-width: 780px) 620px, (min-width: 480px) 392px, 272px';
        } elseif( $sizes == '(max-width: 1100px) 100vw, 1100px' ) {
            $sizes = '(min-width: 1320px) 1100px, (min-width: 1040px) 884px, (min-width: 780px) 748px, (min-width: 480px) 420px, 300px';
        }

        return $sizes;
    }
);

As we can see you can have various image size like one for the single page and smaller ones that are in the sidebar or in the bottom as example. With the condition you can change on the fly the various sizes for all the images you need.

Now do again a check on Pagespeed and the error will gone 🙂

Liked it? Take a second to support Mte90 on Patreon!
Become a patron at Patreon!

Leave a Reply

Your email address will not be published. Required fields are marked *