This post will discuss how to check for the existence of an image at a given URL in JavaScript and jQuery.

1. Using jQuery

To check for the existence of an image with jQuery, you can simply perform an asynchronous HTTP (Ajax) request.

This can be done using the jQuery.ajax() function. You can either call the jQuery.ajax() method to load data from the server, or use other simpler alternatives to fetch data from the server like jQuery.get() and .load(), which uses jQuery.ajax() behind the scenes.

⮚ Using jQuery.ajax()

Edit in JSFiddle

⮚ Using .load()

Edit in JSFiddle

⮚ Using jQuery.get()

Edit in JSFiddle

 
Alternatively, you can dynamically create an image element and attach the onload and onerror event handler using the .on() method.

Edit in JSFiddle

2. Using JavaScript

In plain JavaScript, you can use the powerful Fetch API fetch() method to fetch a resource.

Edit in JSFiddle

 
Alternatively, you can use the Image() constructor, and register the onload and onerror event listener with the addEventListener() method.

Edit in JSFiddle

3. In HTML

If you don’t want to use JavaScript, you can use the onload and onerror attribute of an img element. The onload attribute fires when the image has been loaded, while the onerror attribute fires if an error occurs while loading an image.

Edit in JSFiddle

That’s all about checking for the existence of an image at a given URL in JavaScript and jQuery.