使用jQuery lazyload 实现图片延迟加载

下载地址

使用说明

0. 准备工作

下载jQuery和lazyload 插件(地址如上)

1. HTML

引入jQuery库和lazyload插件

1    <div ></div>
2     <!--<img class="lazy" data-original="img/example.jpg" width="750" height="450">-->
3     <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
4     <script src="../../lib/jquery.lazyload.js"></script>

2. 编写JavaScript

 1  $(function () {
 2 
 3             var images = [
 4                 'https://unsplash.ict/750/450?image=55', // 错误的地址;不会返回图片
 5                 'https://unsplash.it/750/450?image=155',
 6                 'https://unsplash.it/750/450?image=255',
 7                 'https://unsplash.it/750/450?image=355',
 8                 'https://unsplash.it/750/450?image=455',
 9                 'https://unsplash.it/750/450?image=555',
10                 'https://unsplash.it/750/450?image=655',
11                 'https://unsplash.it/750/450?image=5'
12             ],
13             i = images.length,
14             $container = $('#imagesContainer'),
15             placerhold = '../layzr.js/placerhold.gif', // 图片未加载前显示的图片,若不设置,将默认显示灰色
16             imgtemp;
17 
18             while (i--) {
19                 imgtemp = images.shift();
20                 $container.append('<img class="lazy" src="'+placerhold+'" data-original="' + imgtemp + '" width="750" height="450">')
21             }
22 
23             $('img.lazy').lazyload({
24                 effect: 'fadeIn'    // 自定义显示效果(jQuery effect)
25                 , failure_limit: 10 
26                 , threshold: 200    // 当距离图片还有200像素的时候,就开始加载图片。
27                 , event: 'scroll'
28             });
29 
30             // 自定义触发事件
31             // $("img.lazy").lazyload({ event: "click" });
32         });

3. 一些注意事项

3.1 必须设置图片的大小(行内样式或外部CSS都可以),否则插件可能无法达到理想的效果

3.2 可以设置倒计时,在指定的时间后加载图片