Home Web Front-end JS Tutorial Solve the problem of 404 when loading js images_javascript skills

Solve the problem of 404 when loading js images_javascript skills

May 16, 2016 pm 03:33 PM

After operating a website for a long time, it is inevitable that image 404 will appear. The reason may be that the image file does not exist or does not currently exist. A common solution is to hide the 404 image or replace it with the default image .
img tag event attribute
The time attributes that can be used in img tags 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
The commonly used events of the img tag are as follows:

onerror: Triggered when an error occurs during image loading.
onabort: When the image is loading, it is triggered when the user clicks to stop loading. It usually triggers a prompt here: "Image is loading".
onload: Triggered when the image is loaded.
1. Monitor onerror events for images

<img src="someimage.png" onerror="imgError(this);" /> 
 
// 原生JS: 
function imgError(image){ 
 // 隐藏图片 
 image.style.display = 'none'; 
 // 替换为默认图片 
 // document.getElementById("img").setAttribute("src", "images/demo.png"); 
} 
 
// 使用jQuery处理: 
function imgError(image){ 
 $(image).hide(); 
 // $(this).attr("src", "images/demo.png"); 
} 
Copy after login

Note: The processing function needs to be defined in the head to prevent the processing function from not being read when an image loading error occurs
2. Use jQuery to monitor errors

// 通常不会再HTML里面内联js,可以使用.error对图片进行监听处理 
$('#test img').error(function() { 
 $(this).hide(); 
 // $(this).attr("src", "images/demo.png"); 
}); 
Copy after login

Note: jQuery loading needs to be before img, and the processing function needs to be after img
3. Use function processing

// 原生JS解决方案 
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; 
} 
 
// 主要逻辑 
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; 
} 
Copy after login

The above functions have many uses:
1. Get image information: whether the image can be downloaded, image width and height

image('img',{ 
 success : function () { alert(this.width + "-" + this.height); }, 
 failure : function () { alert('image 404!'); }, 
}); 
 
// 验证资源是否下载 
image('images/banner/banner_2.jpg', { 
 success : function () {console.log('sucess')}, 
 failure : function () {console.log('failure')}, 
 target : 'myContainerId', 
 insertBefore : 'someChildOfmyContainerId' 
}); 
Copy after login

2. Download and insert pictures

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); 
Copy after login

The above is the js solution to the 404 problem when loading images. I hope you can gain something.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Replace String Characters in JavaScript

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

Custom Google Search API Setup Tutorial

Example Colors JSON File Example Colors JSON File Mar 03, 2025 am 12:35 AM

Example Colors JSON File

8 Stunning jQuery Page Layout Plugins 8 Stunning jQuery Page Layout Plugins Mar 06, 2025 am 12:48 AM

8 Stunning jQuery Page Layout Plugins

10 jQuery Syntax Highlighters 10 jQuery Syntax Highlighters Mar 02, 2025 am 12:32 AM

10 jQuery Syntax Highlighters

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

Build Your Own AJAX Web Applications

What is 'this' in JavaScript? What is 'this' in JavaScript? Mar 04, 2025 am 01:15 AM

What is 'this' in JavaScript?

10  JavaScript & jQuery MVC Tutorials 10 JavaScript & jQuery MVC Tutorials Mar 02, 2025 am 01:16 AM

10 JavaScript & jQuery MVC Tutorials

See all articles