E
E
eugene1592020-02-19 23:32:51
Web development
eugene159, 2020-02-19 23:32:51

How to write code that replaces the image in background-image with webp (so that pagespeed can see it)?

To determine if webp is supported by the browser, I use the JS code I took from this page:
https://developers.google.com/speed/webp/faq

I call it inside a construct like this:

$(function() {
...
});

In the callback function, if webp is supported, I take the background-image from elements with the desired class via jquery and change the value - I put the path to the webp image. If webp is not supported, then I do nothing.

I check the site in pagespeed - and he (pagespeed) does not seem to see the replacement of paths in background-image with webp. Why is that? Is there any way to write JS code that replaces the image from background-image with webp so that pagespeed can see it? Or is it necessary to remove the background-image and write a data attribute instead - for each DOM element that has a background-image - so that pagespeed does not see the background-image (it will not exist)? Some way too complicated... Yes, and not very true - the paths to the pictures of the appearance of the site should be in styles, not in the layout.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eugene159, 2020-02-23
@eugene159

Everything is simple. When the page is loaded, JS assigns the class "webp" or "no-webp" to the body (depending on whether webp is supported or not). background-image for an element is specified using cascading:

.webp .header-img {
    background-image: url(../img-webp/header-img.webp); 
}

.no-webp .header-img {
    background-image: url(../img/header-img.png); 
}

As a result, pagespeed does not see png, so it does not swear at it.
Details here:
https://css-tricks.com/using-webp-images/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question