We often encounter the problem that img fails to load images due to network problems or too large images, and the page becomes unsightly because of this skipped image. So we need to reload the image when it fails to load
//js method definition function resetImgUrl(imgObj,imgSrc,maxErrorNum){ if(maxErrorNum > 0){ imgObj.onerror=function(){ reSetImgUrl(imgObj,imgSrc,maxErrorNum-1); }; setTimeout(function(){ imgObj.src=imgSrc; },500); }else{ imgObj.onerror=null; imgObj.src="<%=basePath%>images/noImg.png"; } } //call <img onerror='resetImgUrl(this,this.src,3)' src='"+srcStr+"'/> //This logic is extracted from the network http://sunshuij2ee.iteye.com/blog/1727993
Judge the network connection, and ask for pictures when reconnecting the network
var onLine = true var eventList = {} ;//List of events used to store the function to be re executed window.addEventListener('offline',function(){ onLine = false; }) window.addEventListener('online',function(){ if(onLine == false){ onLine = true; reLine(); } }) //When reconnecting to the network, call the function in the event list object again function reLine(){ for(var key in eventList){ if(!eventList[key])continue var arg = eventList[key].arg; var thisOnFn = eventList[key].that; eventList[key].fun.apply(thisOnFn,arg); eventList[key] = null; } } //The network has been disconnected. Store the function in an object function offlined(fun,arg,that){ if(!onLine){ //arg = arguments; var name = fun.name||'__new'; eventList[name] = {}; eventList[name].fun = fun;//Primitive function eventList[name].that = that;//Original context object eventList[name].arg = [].slice.call(arg);//Original parameters return true } return false }
Test it
function aa(){ offlined(aa,arguments,this) for(var i=0 ; i<arguments.length;i++){ console.log(arguments[i]); } } //Disconnect the network and execute the code again aa(123,234,345) //Output once first 123 234 345 //Connect to the network and see the output 123 234 345
Reload logic in combination with the picture above
function resetImgUrl(imgObj,imgSrc,maxErrorNum){ if(offlined(reSetImgUrl,arguments,this))return if(maxErrorNum > 0){ imgObj.onerror=function(){ reSetImgUrl(imgObj,imgSrc,maxErrorNum-1); }; setTimeout(function(){ imgObj.src=imgSrc; },500); }else{ imgObj.onerror=null; imgObj.src="<%=basePath%>images/noImg.png"; } }
If the original content is involved, please indicate the source