Fixed an js image loading 404 problem

  • 2020-09-28 08:43:24
  • OfStack

After you've been running your site for a long time, you can't avoid 404 images because the file doesn't exist or doesn't exist yet. A common solution is to hide or replace the 404 image with the default image.
img tag event properties
The time attributes available for the img tag are:
onabort, onbeforeunload, onblur, onchange, onclick, oncontextmenu, ondblclick, ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop, onerror, onfocus, onkeydown, onkeypress, onkeyup, onload, onmessage, onmousedown, onmousemove, onmouseover, onmouseout, onmouseup, onmousewheel, onresize, onscroll, onselect, onsubmit, onunload
Common events for the img tag are as follows:
onerror: Triggered when an error occurs during image loading.
onabort: When an image loads, it is triggered by the user clicking stop loading, which usually triggers a prompt: "The image is loading".
onload: triggered when the image has finished loading.
1. Monitor the onerror event on the picture


<img src="someimage.png" onerror="imgError(this);" /> 
 
//  native JS: 
function imgError(image){ 
 //  Hidden pictures  
 image.style.display = 'none'; 
 //  Replace with the default image  
 // document.getElementById("img").setAttribute("src", "images/demo.png"); 
} 
 
//  use jQuery To deal with : 
function imgError(image){ 
 $(image).hide(); 
 // $(this).attr("src", "images/demo.png"); 
} 

Note: The handler needs to be defined in head to prevent the image loading error from not reading the handler
2. Use jQuery to listen on error


//  Usually not HTML The inside inline js , can be used .error Listen to the picture  
$('#test img').error(function() { 
 $(this).hide(); 
 // $(this).attr("src", "images/demo.png"); 
}); 

Note: jQuery loading needs to be before img and the handler needs to be after img
3. Use functions


//  native JS The solution  
function $id(id) { 
 return !id || id.nodeType === 1 ? id : document.getElementById(id); 
} 
function isType(o, t) { 
 return (typeof o).indexOf(t.charAt(0).toLowerCase()) === 0; 
} 
 
//  The main logic  
function image(src, cfg) { 
 var img, prop, target; 
 cfg = cfg || (isType(src, 'o') ? src : {}); 
 
 img = $id(src); 
 if (img) { 
  src = cfg.src || img.src; 
 } else { 
  img = document.createElement('img'); 
  src = src || cfg.src; 
 } 
 
 if (!src) { 
  return null; 
 } 
 
 prop = isType(img.naturalWidth,'u') ? 'width' : 'naturalWidth'; 
 img.alt = cfg.alt || img.alt; 
 
 // Add the image and insert if requested (must be on DOM to load or 
 // pull from cache) 
 img.src = src; 
 
 target = $id(cfg.target); 
 if (target) { 
  target.insertBefore(img, $id(cfg.insertBefore) || null); 
 } 
 
 // Loaded? 
 if (img.complete) { 
  if (img[prop]) { 
   if (isType(cfg.success,'f')) { 
    cfg.success.call(img); 
   } 
  } else { 
   if (isType(cfg.failure,'f')) { 
    cfg.failure.call(img); 
   } 
  } 
 } else { 
  if (isType(cfg.success,'f')) { 
   img.onload = cfg.success; 
  } 
  if (isType(cfg.failure,'f')) { 
   img.onerror = cfg.failure; 
  } 
 } 
 
 return img; 
} 

The above functions have many USES:
1. Get picture information: is the picture downloadable? The picture width and height


image('img',{ 
 success : function () { alert(this.width + "-" + this.height); }, 
 failure : function () { alert('image 404!'); }, 
}); 
 
//  Verify that the resource is downloaded  
image('images/banner/banner_2.jpg', { 
 success : function () {console.log('sucess')}, 
 failure : function () {console.log('failure')}, 
 target : 'myContainerId', 
 insertBefore : 'someChildOfmyContainerId' 
}); 

2. Download and insert images


var report = $id('report'), 
 callback = { 
  success : function () { 
   report.innerHTML += '<p>Success - ' + this.src + ' ('+this.offsetWidth+'x'+this.offsetHeight+')</p>'; 
  }, 
  failure : function () { 
   report.innerHTML += '<p>Failure - ' + this.src + ' ('+this.offsetWidth+'x'+this.offsetHeight+')</p>'; 
  }, 
  target : 'target' 
 }; 
 
image('img', callback); 
image('images/banner/banner_2.jpg', callback); 

Above is js for the image loading 404 problem solution, I hope you have a harvest.


Related articles: