webp是一种图像压缩格式,由谷歌推出,开源免费。webp格式图片具有很多优势,相比于传统的png、jpg等在同等图像质量下面,它的图像占有空间更少,因此,可以广泛用于各种对存储空间要求较高的场景中,尤其是web方面。webp支持多种浏览器,例如360、chrome、火狐等,但是,对于IE浏览器它不能直接支持,需要采用一些第三方js插件进行渲染。
本教程针对这个问题进行解决。
完整的资源代码链接:https://download.csdn.net/download/qianbin3200896/12712293
整个解码过程需要依赖两个js插件:polyfills.js和webp-hero.boundle.js。新建index.html,脚本内容如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>webp解码测试</title>
<script src="./polyfills.js"></script>
<script src="./webp-hero.bundle.js"></script>
</head>
<body>
<h1>webp解码测试</h1>
<img alt="" src="test.webp"/>
<script>
// for this demo, you can add "?force" to the url to force webp conversion
var webpSupport = location.search.indexOf("force") !== -1
? Promise.resolve(false)
: undefined
// instance the webp machine
var webpMachine = new webpHero.WebpMachine({webpSupport: webpSupport})
// polyfill this entire document's webp images
webpMachine.polyfillDocument()
</script>
</body>
</html>
这个时候使用Microsoft Edge等浏览器本地打开该html页面,效果如下:
但是如果此时用IE浏览器打开,会发现图片加载不出来。这个问题是因为上述两个js插件比较特殊,只能在服务器部署环境下才能正常使用,直接本地加载会出问题。那么为了验证这个问题,我利用django2简单建设了一个站点,index.html内容如下:
{% load staticfiles %}
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>webp解码测试</title>
<script src="{% static 'polyfills.js' %}"></script>
<script src="{% static 'webp-hero.bundle.js' %}"></script>
</head>
<body>
<h1>webp解码测试</h1>
<img alt="" src="{% static 'test.webp' %}"/>
<script>
// for this demo, you can add "?force" to the url to force webp conversion
var webpSupport = location.search.indexOf("force") !== -1
? Promise.resolve(false)
: undefined
// instance the webp machine
var webpMachine = new webpHero.WebpMachine({webpSupport: webpSupport})
// polyfill this entire document's webp images
webpMachine.polyfillDocument()
</script>
</body>
</html>
然后开启服务器,此时再用ie浏览器(ie11)打开,效果就正常了:
如果熟悉django的读者可以下载完代码后直接运行,查看效果。如果使用java开发web的读者,则需要自行创建一个服务就可以了。