This article mainly shares with you the implementation method of asynchronous loading of images through js. Mainly considering the limitations of the network, for a better user experience, the asynchronous loading and display method is used to load images for img, and the code is directly pasted:
<img onload="getHead(this,url);" src="../../static/xxx/xxx/head.png" > <%--这里注意1,src写在 onload后面2,请给src一个默认的图片路径,不能直接src=""--%>
js:
function getHead(obj,portraitUrl){ //模拟网络延迟请求 setTimeout(function (){ obj.src=../../static/xxx/xxx/add.png; },1000+Math.random()*5000); /* $.ajax({ type: "get", url: portraitUrl, async: true, success: function (portrait) { obj.src=portrait; portraitUrl.onload=null;//这里每次给obj的src赋值后都会执行onload 为了避免无限死循环需要这样置空 } */ }
<img src="http:/xxxx.png" onerror='this.src="../../static/xxx/xxx/head.png" />//这就ok了
<img onload="getHead(this,url);" src="../../static/xxx/xxx/head.png" > <%--这里注意1,src写在 onload后面2,请给src一个默认的图片路径,不能直接src=""--%>
js:
function getHead(obj,portraitUrl){ //模拟网络延迟请求 setTimeout(function (){ obj.src=../../static/xxx/xxx/add.png; },1000+Math.random()*5000); /* $.ajax({ type: "get", url: portraitUrl, async: true, success: function (portrait) { obj.src=portrait; portraitUrl.onload=null;//这里每次给obj的src赋值后都会执行onload 为了避免无限死循环需要这样置空 } */ }
<img src="http:/xxxx.png" onerror='this.src="../../static/xxx/xxx/head.png" />//这就ok了
Related recommendations:
The above is the detailed content of Implementation method of asynchronously loading images through js. For more information, please follow other related articles on the PHP Chinese website!