将以下步骤作为工作清单,并根据项目的证据、范围和限制进行调整。
实用步骤
- 打开要检查的页面和浏览器开发者控制台。检查移动端溢出时,先使用响应式模式。
- 审查代码,将完整代码片段粘贴到控制台并按 Enter。脚本读取当前页面;只有 sitemap 元数据工具和同源检查工具会在有限范围内发出请求。
- 查看控制台输出或下载的 CSV/JSON。浏览器策略、身份验证和服务器不支持的方法可能导致部分检查无法得出结论。
(() => {
const MAX_IMAGES = 5000;
const imageCount = document.images.length;
const images = Array.from({ length: Math.min(imageCount, MAX_IMAGES) }, (_, index) => document.images[index]).map((img) => {
const rect = img.getBoundingClientRect();
return {
src: img.currentSrc || img.src,
alt: img.hasAttribute('alt') ? img.alt : '[missing alt attribute]',
altAttribute: img.hasAttribute('alt') ? 'present' : 'missing',
naturalSize: img.naturalWidth + 'x' + img.naturalHeight,
renderedSize: Math.round(rect.width) + 'x' + Math.round(rect.height),
widthAttribute: img.hasAttribute('width') ? img.getAttribute('width') : '',
heightAttribute: img.hasAttribute('height') ? img.getAttribute('height') : '',
loading: img.loading || '',
loadState: !img.getAttribute('src') && !img.getAttribute('srcset') ? 'no source' : !img.complete ? img.loading === 'lazy' ? 'lazy: not loaded yet' : 'loading' : img.naturalWidth > 0 ? 'loaded' : 'failed',
excessPixelResolution: rect.width > 0 && img.naturalWidth > rect.width * devicePixelRatio * 2,
};
});
console.table(images);
const quote = (value) => '"' + String(value).replace(/[\u0000-\u0020]*[=+\-@]/, (match) => "'" + match).replace(/"/g, '""') + '"';
const rows = [['src', 'alt', 'alt attribute', 'natural size', 'rendered size', 'width', 'height', 'loading', 'load state', 'excess pixel resolution'], ...images.map((img) => [img.src, img.alt, img.altAttribute, img.naturalSize, img.renderedSize, img.widthAttribute, img.heightAttribute, img.loading, img.loadState, img.excessPixelResolution])];
const a = document.createElement('a');
a.href = URL.createObjectURL(new Blob(['\uFEFF' + rows.map((row) => row.map(quote).join(',')).join('\r\n')], { type: 'text/csv;charset=utf-8' }));
a.download = 'page-images.csv'; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 1000);
console.info('Images found:', images.length, '· missing alt:', images.filter((img) => img.altAttribute === 'missing').length, '· failed:', images.filter((img) => img.loadState === 'failed').length, '· lazy and not loaded yet:', images.filter((img) => img.loadState === 'lazy: not loaded yet').length);
if (imageCount > MAX_IMAGES) console.warn('Only the first ' + MAX_IMAGES + ' of ' + imageCount + ' images were checked.');
})();运行前请先审查代码。脚本读取当前页面;只有 sitemap 和链接审查工具会在有限范围内发出同源请求。请求不携带 cookies;脚本不会更改网站内容。