Home > Web Front-end > JS Tutorial > How Can I Efficiently Handle Broken Images in My Web Pages Using jQuery or JavaScript?

How Can I Efficiently Handle Broken Images in My Web Pages Using jQuery or JavaScript?

DDD
Release: 2024-12-23 18:51:19
Original
455 people have browsed it

How Can I Efficiently Handle Broken Images in My Web Pages Using jQuery or JavaScript?

Handling Broken Images with jQuery or JavaScript

Problem:
A web page with numerous images encounters broken image instances due to unavailability.

jQuery Approach:

  1. Acquire the image elements: $("img").
  2. Filter broken images: $brokenImages = $("img").filter(function() { return this.complete && !this.naturalWidth; }).
  3. Replace 'src' property with a placeholder image: $brokenImages.attr("src", "/broken-image.png").

JavaScript onError Event:

An alternative approach involves handling the onError event for each image to reassign its source directly.

  1. Define an image error handling function:
function imgError(image) {
    image.onerror = "";
    image.src = "/images/noimage.gif";
    return true;
}
Copy after login
  1. Utilize the function in HTML:
<img src="image.png" onerror="imgError(this);"/>
Copy after login
  1. Or without a function:
<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />
Copy after login

Browser Compatibility:

For the onError event handling approach, please refer to the compatibility table at:

http://www.quirksmode.org/dom/events/error.html

The above is the detailed content of How Can I Efficiently Handle Broken Images in My Web Pages Using jQuery or JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template