应用我编写的脚本后,google page speed insight 仍会向我显示以下建议:1. 适当调整图像尺寸;2. 图像没有明确的宽度和高度这是脚本...
在应用我编写的脚本后,google page speed insight 仍向我显示以下建议: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);
};
});
});