基于javascript实现图片预加载(2)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> body{ margin: 0; } img{ width: 100px; height: 100px; } </style> </head> <body> <button>载入图片</button> <img src="https://www.jb51.net/img/test.png" alt="测试"> <script> var oBtn = document.getElementsByTagName('button')[0]; var oImg0 = document.images[0]; var array = ["img/img1.gif","img/img2.gif","img/img3.gif","img/img4.gif"] var iNow = -1; oBtn.onclick = function(){ iNow++; iNow = iNow%4; oImg0.src = array[iNow]; } function preLoadImg(arr,callback){ var aImages = []; var iDown = 0; for(var i = 0; i < arr.length; i++){ aImages[i] = new Image(); aImages[i].onload = function(){ loadImgTest(arr,callback); }; aImages[i].onerror = function(){ loadImgTest(arr,callback); }; aImages[i].src = arr[iDown]; } function loadImgTest(arr,callback){ iDown++; if(iDown == arr.length){ alert('ok'); callback && callback.call(aImages); } } } preLoadImg(array,function(){ console.log(this[0].width); }); </script> </body> </html> 应用:预加载模糊变清晰 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> body{ margin: 0; } img{ width: 500px; height: 500px; } </style> </head> <body> <button>载入图片</button> <img src="#" alt="测试"> <script> var oBtn = document.getElementsByTagName('button')[0]; var oImg0 = document.images[0]; var arrayB = ["img/img1.gif","img/img2.gif","img/img3.gif","img/img4.gif"]; var arrayL = ["img/img1.jpg","img/img2.jpg","img/img3.jpg","img/img4.jpg"]; var iNow = -1; oBtn.onclick = function(){ iNow++; iNow = iNow%4; oImg0.src = arrayL[iNow]; aftLoadImg(arrayB,oImg0); } var aImages = []; window.onload = function(){ preLoadImg(arrayL); } function preLoadImg(arr){ for(var i = 0, len = arr.length; i < len; i++){ aImages[i] = new Image(); aImages[i].src = arr[i]; } } function aftLoadImg(arr,obj){ var oImg = new Image(); oImg.onload = function(){ obj.src = arr[iNow]; } oImg.src = arr[iNow]; } </script> </body> </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgwfds.html