图片占位符,图片由于诸如过大导致浏览器渲染慢、服务器端响应时间过长、页面需要加载的图片过多等原因导致图片未加载。
某些图片未成功渲染场景下,希望页面结构能大致保持不变。
注: 同类型的先驱:http://holderjs.com/
由于当前placeholder.js已经满足需求,因此暂不对比更加广泛使用的holderjs
一、简介
placeholder.js是一款轻量级的可在浏览器端生成占位图片的javascript库插件。该图片占位插件大小小于1kb,不依赖于任何js框架,并提供完善的配置参数和简单的方法。
二、使用步骤
1. 引用类库
1
| <script src="http://cdn.bootcss.com/placeholder.js/3.1.0/placeholder.js"></script>
|
2. 使用方法
Programmatic use API to process image: placeholder.getData(opts)
通过js程序设置图片src内容。
1
| document.getElementById('img_holder').setAttribute('src', window.placeholder.getData(opts));
|
Image onerror event
在img标签上添加onerror监听事件。
1
| onerror="this.src=placeholder.getData({size: '256x128', text: 'Image 404'})"
|
Use image config attribute.
1 2 3
| <img class="placeholder"> <img options="size=256x128&text=Hello!" class="placeholder"> <img options="size=256x128&text=Hello%2525%26%3DWorld" class="placeholder">
|
这种方式,有几点使用注意事项:
- 需要在所有img标签后添加渲染语句
1 2 3 4
| <script type="text/javascript">
placeholder.render() </script>
|
- options内text值需要做encodeURIComponent
- img标签必须包含名为placeholder的class属性值
三、实例
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
| <!DOCTYPE html> <html>
<head> <title>placeholder实例</title> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://cdn.bootcss.com/placeholder.js/3.1.0/placeholder.js"></script> </head>
<body> <p>1. Programmatic use API to process image: placeholder.getData(opts)</p> <pre>document.getElementById('img_holder').setAttribute('src', window.placeholder.getData(opts));</pre> <img id="img_holder" src=""> <script type="text/javascript"> var opts = { size: '256x128', font: { style: 'oblique', }, text: 'Hello World' } document.getElementById('img_holder').setAttribute('src', window.placeholder.getData(opts)); </script> <p>2. Image onerror event</p> <pre>onerror="this.src=placeholder.getData({size: '256x128', text: 'Image 404'})"</pre> <img id="img_holder2" src="404.png" onerror="this.src=placeholder.getData({size: '256x128', text: 'Image 404'})">
<p>3. Use image config attribute.</p> <pre><img class="placeholder"></pre>
<img class="placeholder"> <pre><img options="size=256x128&text=Hello!" class="placeholder"></pre>
<img options="size=256x128&text=Hello!" class="placeholder"> <pre><img options="size=256x128&text=Hello!&bgcolor=#ccc&color=#969696&fstyle=oblique&fweight=bold&fsize=40&ffamily=consolas" class="placeholder"></pre> <img options="size=256x128&text=Hello!&bgcolor=#ccc&color=#969696&fstyle=oblique&fweight=bold&fsize=40&ffamily=consolas" class="placeholder">
<script type="text/javascript"> placeholder.render() </script>
</body>
</html>
|
四、参考文档
官方地址:http://placeholder.cn/
使用实例:http://placeholder.cn/doc/demo.html