var img = new image(); img.src = "小图占位.jpg"; //加载载占位的,和html在同一文件夹下,实际也要onlaod加载,本地加载速度快一点 img.onload = function(){ document.querySelector("body").appendChild(img); } var img_r = new image();//这个东西能够放到默认图片加载的onload里 img_r.src = "大图真实.jpg"; //下载真实的,远程服务器请求 img_r.onload = function(){ img.src = img_r.src //下载完后,替换占位 }
1,第一种方法,小图占位
2,第二种方法,容器背景图占位,img下载后放到容器里,遮住容器背景图html
注释:服务器的图片在src以后就开始下载了,可是只有当图片onload(也就是图片下载完成)后往body里添加才会直接显示出来。。服务器
$("#main_scroll").empty().html(data); var imgs = document.querySelectorAll("img"); var img_arry = []; for(var i = 0 ;i < imgs.length; i++){ img_arry[i] = imgs[i].src; imgs[i].style.height = SW+"px"; imgs[i].style.width = SW+"px"; (function(index){ imgs[index].src = 'img/defalut.png'; imgs[index].onload = function(){ var temp_img = new Image(); temp_img.src = img_arry[index]; var height = (SW/this.naturalWidth>=1?1:SW/this.naturalWidth)*this.naturalHeight; var width = (SW/this.naturalWidth>=1?1:SW/this.naturalWidth)*this.naturalWidth; imgs[index].src = temp_img.src; imgs[index].style.height = height+"px"; imgs[index].style.width = width+"px"; } imgs[index].onerror = function(){ console.log("默认图片加载出错了"+index) } })(i) };