johntrepreneur
johntrepreneur

Reputation: 4694

How to valiate if list of image URLs exist before feeding them to javascript plugin?

Does anyone know a lightweight way to validate if an image URL exists or not?

I have a list of images (some are 404's) that I'm feeding to my jquery image viewer plugin (or any other javascript lightbox plugin for that matter) which doesn't deal well with 404 image URLs.

I know you can use the onerror event available on the html img element, which is probably the most efficient and I've used before for other image viewer plugins that require the use of the <img> tag, but not all the plugin's use that tag (inlcuding my current one), so I'm left wondering how to validate the URLs so the plugin doesn't choke on them?

I suppose I could create an <img> element, set display:none, set each image one-at-a-time, and find out if it's valid by checking the onerror event, but that seems inefficient. Any other easier way? You'd think some fundamental behavior of these plugins would be to check for that, but I haven't found one yet that does and meets my criteria.

Upvotes: 1

Views: 258

Answers (2)

johntrepreneur
johntrepreneur

Reputation: 4694

I ended up going with @Volatile's solution (from the comments under the question) and adding the images to hidden img tags and then using the imagesLoaded plugin on that group of hidden img tags to filter only the ones that loaded successfully. Then the image viewer plugin was happy with the non-404 images and just retrieved them from the browser cache.

Upvotes: 0

jszobody
jszobody

Reputation: 28911

Make a HEAD Ajax request

Are your images hosted on the same domain? If so, you could make an Ajax type "HEAD" request to see if it is a 404, without retrieving the contents of the image itself. This should make your initial check quite fast and efficient. See this thread for an example that I think is somewhat similar to what you are looking to accomplish:

Ajax HEAD request via Javascript/jQuery

Do it server side

If your images are not on the same domain, or you need to support older browsers that may not be able to do HEAD Ajax requests, I'd be tempted to verify your URLs server side. Do this before the page loads, or if you can't, make an Ajax call to your own server side script. The server side script can get the headers for each URL (again without pulling the image data itself) and tell you which ones are valid.

Upvotes: 1

Related Questions