<!DOCTYPE html> <html> <head> <title>图片无序预加载-优化</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <meta name="keywords" content="your keywords"> <meta name="description" content="your description"> <style> *{margin: 0;padding: 0} #box{width: 1024px;height: 500px;margin: 50px auto;} img{width: 1024px;height: 450px;border: 1px solid red;} #click{text-align: center;} </style> </head> <body> <div id="box"> <img src="" alt=""> <div id="click"> <a href="" id="prev">上一页</a> <a href="" id="next">下一页</a> </div> </div> <script src="../../js/jquery-3.2.0.js"></script> <script> var imgs = [ 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=4116894745,1605052943&fm=26&gp=0.jpg', 'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=644449983,791694252&fm=26&gp=0.jpg', 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3225666097,3247550499&fm=26&gp=0.jpg', 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3014020588,2537118876&fm=26&gp=0.jpg', 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2171490910,189745274&fm=26&gp=0.jpg', 'https://coding.net/u/ready-/p/study/git/raw/master/img/Magnifier.png', 'https://coding.net/u/ready-/p/study/git/raw/master/img/Magnifier.png' ]; var index = 0, curImg = 0, num = 1,//预加载当前图片后num张图片.. len = imgs.length; $(function () { $('img').attr('src',imgs[0]); $('a').on('click',function(){ curindex = (this.id === 'prev') ? Math.max(0,--index) : Math.min(imgs.length-1,++index); $('img').attr('src',imgs[curindex]); load(); return false; }) }) function load(){ var imgObj = new Image(); $(imgObj).on('load error',function(){ /*if(curImg >= len){ }else{ load(); }*/ if(curImg <= index+num){ load(); curImg++; } }) imgObj.src = imgs[curImg]; } load(); </script> </body> </html>
掌声PAPAPA