尝试通过上传不同尺寸的图像并编写 javascript 代码来使我网站上的所有图像都能响应

问题描述 投票:0回答:1

应用我编写的脚本后,Google 页面速度洞察仍然向我显示建议:1. 正确调整图像大小和 2. 图像没有明确的宽度和高度

这是我正在使用的脚本。我也指定了宽度和高度,但它不能正常工作。

document.addEventListener('DOMContentLoaded', function() {
    const images = document.querySelectorAll('img');

    images.forEach(img => {
        // Skip images with the attribute "data-no-responsive"
        if (img.hasAttribute('data-no-responsive')) {
            return;
        }

        const src = img.src;
        const fileName = src.split('/').pop().split('.')[0];
        const originalExt = src.split('.').pop();
        
        // Directories for different sizes
        const smallDir = 'assets/img/small/';
        const middleDir = 'assets/img/middle/';
        const originalDir = 'assets/img/';

        // new image object to get the original width and height
        const tempImg = new Image();
        tempImg.src = src;
        tempImg.onload = function() {
            const originalWidth = tempImg.width;
            const originalHeight = tempImg.height;
            const middleWidth = originalWidth / 2;
            const middleHeight = originalHeight / 2;
            const smallWidth = originalWidth / 4;
            const smallHeight = originalHeight / 4;

            // Rounded dimensions
            const roundedOriginalWidth = Math.round(originalWidth);
            const roundedOriginalHeight = Math.round(originalHeight);
            const roundedMiddleWidth = Math.round(middleWidth);
            const roundedMiddleHeight = Math.round(middleHeight);
            const roundedSmallWidth = Math.round(smallWidth);
            const roundedSmallHeight = Math.round(smallHeight);

            // srcset URLs
            const smallSrc = `${smallDir}${fileName}-400w.webp`;
            const middleSrc = `${middleDir}${fileName}-800w.webp`;
            const originalSrc = `${originalDir}${fileName}.${originalExt}`;

            // Update the img element with srcset, sizes, and width/height attributes
            img.srcset = `${smallSrc} ${roundedSmallWidth}w, ${middleSrc} ${roundedMiddleWidth}w, ${originalSrc} ${roundedOriginalWidth}w`;
            img.sizes = '100vw'; 

            // CSS to ensure the image fills the width of its container
            img.style.width = '100%';
            img.style.height = 'auto';
            img.style.maxWidth = '100%'; // Prevent the image from exceeding the width of its container

            // Explicit width and height attributes
            img.setAttribute('width', roundedOriginalWidth);
            img.setAttribute('height', roundedOriginalHeight);
        };
    });
});

javascript responsive responsive-images
1个回答
0
投票

我不确定客户端 JavaScript 是否会改善此问题。我解释这些页面速度消息的方式:

适当大小的图像

当您将高分辨率图像放入较小的容器中时。 了解更多

图像没有明确的宽度和高度

这与 HTML 标记本身有关,

<img src="image.jpg" width="400" height="300" alt="My Image">
,以便浏览器能够更好地呈现页面。 了解更多

© www.soinside.com 2019 - 2024. All rights reserved.