webp嗅探丨技术开发分享录

webp嗅探

{{ detail.nickname }}

转载 翻译 {{ formatTime(detail.create_time) }} 字数 {{ detail.content && detail.content.length }} 阅读 {{ detail.read_num }} {{ formatTag(v) }}

"## 一、google官方嗅探代码\n\n在浏览器中可以采用JavaScript检测是否支持WebP,对支持WebP的用户输出WebP图片,否则输出其他格式的图片。\n\n```\nfunction check_webp_feature(feature, callback) {\n  var kTestImages = {\n    lossy: \"UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA\",\n    lossless: \"UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==\",\n    alpha: \"UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==\",\n    animation: \"UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/////AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gcA\"\n  };\n  var img = new Image();\n  img.onload = function() {\n    var result = (img.width > 0) && (img.height > 0);\n    callback(feature, result);\n  };\n  img.onerror = function() {\n    callback(feature, false);\n  };\n  img.src = \"data:image/webp;base64,\" + kTestImages[feature];\n}\n\ncheck_webp_feature('lossy', function(feature, status) { \n  console.log(feature, status); // lossy true\n});\n```\n\n## 二、canvas方式\n\n```\nvar isSupportWebp = function () {\n  try {\n    return document.createElement('canvas').toDataURL('image/webp', 0.5).indexOf('data:image/webp') === 0;\n  } catch(err) {\n    return false;\n  }\n}\n\nisSupportWebp()\n```\n\n## 三、请求头\n\n在服务端根据请求header信息判断浏览器是否支持webp\n\n谷歌浏览器上请求图片 header是这样的:\n\n![](https://upload-images.jianshu.io/upload_images/5308475-56755fe184d5f265.png?imageMogr2/auto-orient/strip|imageView2/2/w/814/format/webp)\n\nIE 浏览器请求图片 header是这样的:\n\n![](https://upload-images.jianshu.io/upload_images/5308475-5b6d8cdf3623e0dc.png?imageMogr2/auto-orient/strip|imageView2/2/w/670/format/webp)\n\n在图片请求发出的时候,`Request Headers` 里有 `Accept`,服务端可以根据 `Accept` 里面是否有 `image/webp` 进行判断。\n\n**附加:**\n\npicture标签兼容\n\n```html\n<picture>\n  <source type=\"image/webp\" srcset=\"images/logo.webp\">\n  <img src=\"images/logo.jpg\" alt=\"logo\">\n</picture>\n```\n\n参考链接:\n\n- https://aotu.io/notes/2016/06/23/explore-something-of-webp/index.html\n- http://jartto.wang/2020/05/02/webp-practice/#\n- https://www.jianshu.com/p/3ab716ee1a2e"
PS:写作不易,如要转裁,请标明转载出处。

如果此篇对您有帮助,可小额赞助,以兹鼓励!

猜你想看