WebP
WebP
Can i use WebP
根据accept请求头判断
如果是Chrome浏览器它会在请求头
accept
中加入image/webp
。1
2
3
4
5accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
or
accept: image/webp,image/apng,image/*,*/*;q=0.8前端检测
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20// check_webp_feature:
// 'feature' can be one of 'lossy', 'lossless', 'alpha' or 'animation'.
// 'callback(feature, result)' will be passed back the detection result (in an asynchronous way!)
function check_webp_feature(feature, callback) {
var kTestImages = {
lossy: "UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",
lossless: "UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==",
alpha: "UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==",
animation: "UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/////AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gcA"
};
var img = new Image();
img.onload = function () {
var result = (img.width > 0) && (img.height > 0);
callback(feature, result);
};
img.onerror = function () {
callback(feature, false);
};
img.src = "data:image/webp;base64," + kTestImages[feature];
}
例子
如果使用了内容协商
的方式返回了webp格式的图片,在使用CDN或缓存的情况我们需要在响应头加入Vary字段来告诉该如何缓存。
1 | location ~ ^/webp/(.*)\.(jpg|png|gif)$ { |
访问 http://example.kekek.cc/webp/2018-FIFA-World-Cup.png 查看
下面两幅图分别为在Chrome和Firefox浏览器中访问的响应:
Chrome
Firefox
参考
本站采用「署名 4.0 国际」进行许可。