K
K
konstant1n132021-04-09 22:56:42
JavaScript
konstant1n13, 2021-04-09 22:56:42

Google PageSpeed ​​doesn't see my webp image replacement script. What to do?

Good day to all!

I wrote a changeImgsFormat.js script that changes the attributes of all img and image from png / jpg to webp files, which are in the folder of the same name in each directory. The script is included in head.
Why doesn't Google PageSpeed ​​see it?
And how can I fix it?

I can't change image tags to img tags because images have masks applied to them that cut them to the right shape.

Here's the site:
umark.it

Here's my script that takes all the img and image tags from html and changes the image source to a webp image if the browser supports it.

// Функция проверки поддержки браузером формата webp
const canUseWebp = function () {
    // Создаем элемент canvas
    let elem = document.createElement('canvas');
    // Приводим элемент к булеву типу
    if (!!(elem.getContext && elem.getContext('2d'))) {
        // Создаем изображение в формате webp, возвращаем индекс искомого элемента и сразу же проверяем его
        return elem.toDataURL('image/webp').indexOf('data:image/webp') == 0;
    }
    // Иначе Webp не используем

    return false;
}()


// Устанавливаем тэгу html класс webp или no-webp, чтобы в стилях ставить нужные картинки
const setClassToBody = (() => {
        document.documentElement;
        if (canUseWebp) {
            document.documentElement.classList.add('webp')
        } else {
            document.documentElement.classList.add('no-webp')
        }
    })();




document.addEventListener('DOMContentLoaded', () => {
    const allImgs = [document.querySelector('.why__lightning'), document.querySelector('.why__target')];
    //здесь будут все тэги, для которых будем менять источник изображения, если браузер поддерживает webp


    const workersImgs = document.querySelectorAll('.animated-mask__img');
    const caseItemsImgs = document.querySelectorAll('.case__item');



    function iterateArray(data) {

        const {
            arrayToIterate,
            arrayToPush
        } = data;


        for (let i = 0; i < arrayToIterate.length; i++) {

            arrayToPush.splice(2, 0, arrayToIterate[i])
        }



    }

    (function pushEverythingToAllImgs() {

        iterateArray({
            arrayToIterate: workersImgs,
            arrayToPush: allImgs
        });

        iterateArray({
            arrayToIterate: caseItemsImgs,
            arrayToPush: allImgs
        });


    })()



    allImgs.forEach((item, index) => {
        const content = item.outerHTML;

        if (canUseWebp) {
            function changeDiretionToFile(data) {
                const {
                    typeOfSource,
                    dirToImg,
                    newExt
                } = data;


                const srcArray = dirToImg.split('/');

                const lastSrcArrayItem = srcArray[srcArray.length - 1];

                const fileName = lastSrcArrayItem.split('.');

                fileName[1] = newExt; //2ой элемент массива из имени файлы, т.е. расширение файла

                const fileNameNewExt = fileName.join('.')


                srcArray[srcArray.length - 1] = `webp/${fileNameNewExt}`

                //  console.log(srcArray[srcArray.length-1])

                const newDirectionToFile = srcArray.join('/')

                //console.log(newDirectionToFile)

                item.setAttribute(typeOfSource, newDirectionToFile)

                // item.setAttribute('src',)

            }


            if (content.includes('<img')) {
                const typeOfSource = 'src';
                const src = item.getAttribute('src');


                changeDiretionToFile({
                    typeOfSource: 'src',
                    dirToImg: src,
                    newExt: 'webp'
                })

                //webp-картинки лежат рядом с картинками в папке webp/, чтобы не было путаницы, если картинок много

            }

            if (content.includes('<image')) {
                const href = item.getAttribute('href');


                changeDiretionToFile({
                    typeOfSource: 'href',
                    dirToImg: href,
                    newExt: 'webp'
                })

            }

        }

    });



})


Google PageSpeed ​​complains about these pictures, although the script works correctly
6070b148ac09c297766172.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
iBird Rose, 2021-04-09
@konstant1n13

well, as if from the fact that you changed them - they did not stop loading in the browser. you actually made it worse. you first load jpg / png, and then in addition webp.

T
ThunderCat, 2021-04-10
@ThunderCat

Here's my script that takes all the img and image tags from html and changes the image source to a webp image if the browser supports it.
Discover the picture tag! And yes - iBird Rose is absolutely right, you've only made it worse.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question