图片预加载的特点
1、提前加载所需图片
2、更好的用户体验
图片预加载分为两类
1、无序加载
(1)图片相册
(2)qq表情
2、有序加载
(3)漫画加载
实例1图片相册之使用预加载(不用插件)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>图片预加载之无序加载(不用插件)</title> <script src="http://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script> <style media="screen"> html,body{ height: 100%; } .box{ text-align: center; } .btn{ display: inline-block; height: 30px; line-height: 30px; border: 1px solid #ccc; padding: 0 10px; margin-right: 50px; color: #333; } .btn:hover{ background-color: #eee; } .loading{ position: fixed; top:0; left: 0; width: 100%; height: 100%; background-color: #eee; text-align: center; font-size: 30px; } .progress{ margin-top: 300px; } </style> </head> <body> <div class="box"> <img src="//yx-public.oss-cn-hangzhou.aliyuncs.com/adc98e6055dea2f7d70dbf29330836ee.jpeg" alt="" id="img" width="1200"> <p> <a href="javascript:;" class="btn" data-control="prev">上一页</a> <a href="javascript:;" class="btn" data-control="next">下一页</a> </p> </div> <div class="loading"> <p class="progress">0%</p> </div> <script type="text/javascript"> var imgs=[ '//yx-public.oss-cn-hangzhou.aliyuncs.com/adc98e6055dea2f7d70dbf29330836ee.jpeg', '//yx-public.oss-cn-hangzhou.aliyuncs.com/14d609f923961c318f13c7fd7e8ac3f6.jpeg', 'http://yx-public.oss-cn-hangzhou.aliyuncs.com/00d979a61282883a468e7a54bb724063.jpeg', 'http://yx-public.oss-cn-hangzhou.aliyuncs.com/c2a69a01f45fc6d2bfb1aa68ea578eba.jpeg', 'http://yx-public.oss-cn-hangzhou.aliyuncs.com/574ce331b164e265ccaaadc975d95bf0.jpeg', 'http://yx-public.oss-cn-hangzhou.aliyuncs.com/077054ab22e6920e4277e5cbe0b3290d.jpeg', 'http://img.article.pchome.net/00/44/23/20/pic_lib/wm/2.jpg', 'http://lcd.yesky.com/imagelist/2009/044/404q4y8g4m0p.jpg', 'http://lcd.yesky.com/imagelist/2009/044/cgro54wt2t2x.jpg' ]; var index = 0, len = imgs.length, count = 0, $progress = $('.progress'); $.each(imgs, function(i,src){ var imgObj = new Image(); $(imgObj).on('load', function(){ $progress.html(Math.round((count + 1)/ len * 100) + '%' ); if( count >= len - 1 ){ $('.loading').hide(); document.title = '1/' + len; } count++; }) imgObj.src = src }) $('.btn').on('click',function(){ if( 'prev' === $(this).data('control') ){ //上一张 index = Math.max(0, --index); }else{//下一张 index = Math.min(len-1, ++index) } document.title = (index + 1) + '/' + len; $('#img').attr('src', imgs[index]); }) </script> </body> </html>