.NET Daily

How to check and replace a missing image with jQuery

Introduction

Darius

Darius

Darius Dumitrescu is a creative Senior CMS Consultant with in depth .NET knowledge, focused on Web Development and Architecture Design.


LATEST POSTS

My View on the Life cycle of a Fixed Cost Web Project 01st July, 2018

How to Deliver Accurate Project Status Reports 21st April, 2018

Javascript

How to check and replace a missing image with jQuery

Posted on .

There are cases when you want to reference in your website some images from an external source. If those images are displayed on the homepage or in any other visible area of your website then you have to be sure that the external images are always available otherwise the design or the layout of the page might be affected by a connection problem on the external server or by a server downtime.

In order avoid any design or layout issues, you need to verify at every page load if the images are loaded or not. You can do that as follows:

$(document).ready(function() {

$("#myimage").load(function() {
  console.log('Image loaded!');
}).error(function() {console.log("Image not loaded!"); this.src ="Images/image-missing.png";});

});

In the code lines above, the image with the id “myimage” is verified at every page load if it was successfully loaded, otherwise it is replaced with a default image.

The above code can also be achieved with plain JavaScript:

var img = document.getElementById('html5logo');

img.onload = function() {
    console.log('image is loaded');
};
img.onerror = function(){
	console.log('image is not loaded');
	img.src='Images/image-missing.png';
};

Of course, the key event here is onerror for JavaScript and error for jQuery. The onload event is used only checking whether the image was loaded or not.

You can download a very basic demo from below.

Attachments

Darius

Darius

Darius Dumitrescu is a creative Senior CMS Consultant with in depth .NET knowledge, focused on Web Development and Architecture Design.

There are no comments.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

View Comments (0) ...
Navigation