实现全站图片使用avif格式,并优化不兼容avif的配置

本站使用EO来显示avif

腾讯的边缘安全加速平台 EO平台是我们现在常用的全站加速方式之一,边缘安全加速平台 EO的媒体加速是限时免费的。

示例:https://example.com/1.jpg

对于不兼容的avif格式浏览器使用以下js代码实现切换至webp格式

为了确保处理懒加载图片,我们需要确保观察到所有图片加载事件,并在图片加载完成后替换它们的 URL。这可以通过监听 load 事件来实现。下面是代码,结合了 MutationObserver 和 load 事件监听:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
document.addEventListener('DOMContentLoaded', function() {
console.log("DOM content loaded"); // 检查DOM是否加载完成

// 从页面中提取所有带有 AVIF 参数的图片链接
function getAllAvifImages() {
const images = document.querySelectorAll('img');
return Array.from(images).filter(img => img.src.includes(''));
}

// 检测浏览器是否支持AVIF格式
function supportsAvif(url) {
return new Promise(resolve => {
const avif = new Image();
avif.src = url;
avif.onload = () => {
console.log("AVIF supported");
resolve(true);
};
avif.onerror = () => {
console.log("AVIF not supported");
resolve(false);
};
});
}

// 替换图片URL中的 avif 参数为 webp
function replaceAvifWithWebp(images) {
images.forEach(img => {
if (img.src.includes('')) {
console.log("Replacing AVIF with WebP for image:", img.src);
img.src = img.src.replace('', '?eo-img.format=webp');
console.log("New image src:", img.src);
}
});
}

const firstAvifImage = getAllAvifImages()[0]; // 获取第一个带有AVIF参数的图片
console.log("First AVIF Image:", firstAvifImage); // 输出第一个AVIF图片

if (firstAvifImage) {
supportsAvif(firstAvifImage.src).then(supported => {
if (!supported) {
const images = getAllAvifImages();
replaceAvifWithWebp(images);

// 使用 MutationObserver 监控 DOM 的变化
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
if (mutation.addedNodes.length) {
mutation.addedNodes.forEach(node => {
if (node.tagName === 'IMG' && node.src.includes('')) {
replaceAvifWithWebp([node]);
}
});
}
});
});

observer.observe(document.body, {
childList: true,
subtree: true
});

// 监听所有懒加载图片的load事件
document.addEventListener('load', event => {
if (event.target.tagName === 'IMG' && event.target.src.includes('')) {
replaceAvifWithWebp([event.target]);
}
}, true);
} else {
console.log("AVIF images will be used.");
}
});
} else {
console.log("No AVIF images found on the page.");
}
});