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.
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.