Solve the problem of 404 when loading js images_javascript skills
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"); }
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"); });
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; }
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' });
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);
The above is the js solution to the 404 problem when loading images. I hope you can gain something.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.
