Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Catching an image load event error 404, can it be done?

I'm basically looping over a bunch of youtube video url's to get each video's id code.

I then reiterate over all 'thumbnail' images in a list and replace the source with the youtube video thumbnail url.

The problem I am currently running into is that if the video has been removed from youtube the resulting image source will not return a functioning image url, however the replace is still firing thus a broken image url is placed into the list.

How can I get jQuery to detect whether the url is actually still working before replacing the initial image source with the thumbnail source?

Here is my code that loops over the youtube clips on the page and filters their IDs:

function generateYoutubeThumbnails() {
    var YTT = {};
    YTT.videos = $('.video-thumbnail'); // the placeholder thumbnail image

    YTT.videos.each(function(i) {
        YTT.url = $(this).attr('data-videourl'); // the youtube full url, eg: http://www.youtube.com/watch?v=F52dx9Z0L5k
        YTT.videoId = YTT.url.replace(/(.+?)watch\?v=/gi,'').replace(/\&(.+)$/gi,''); // find and replace to get just the id: eg: F52dx9Z0L5k

        YTT.snip = 'http://img.youtube.com/vi/'+ YTT.videoId +'/hqdefault.jpg'; // the thumbnail url which would return: http://img.youtube.com/vi/F52dx9Z0L5k/hqdefault.jpg in this case.

        $(this).attr('src', YTT.snip); // replace the placeholder thumbnail with the proper youtube thumbnail that we got above
    });
}
generateYoutubeThumbnails();

Any ideas on how I can stop the find and replace of the last step if the resulting url is not working?

like image 253
Jannis Avatar asked Dec 05 '10 23:12

Jannis


People also ask

How can we detect an image been fully loaded in the browser?

The image is considered completely loaded if any of the following are true: Neither the src nor the srcset attribute is specified. The srcset attribute is absent and the src attribute, while specified, is the empty string ( "" ). The image resource has been fully fetched and has been queued for rendering/compositing.

How can you tell if an image is loaded?

Using attributes of <img> to check whether an image is loaded or not. The attributes we will use are: onload: The onload event is triggered when an image is loaded and is executed. onerror: The onerror event is triggered if an error occurs during the execution.


1 Answers

jQuery

$('img').bind('error', function() {
   alert('image did not load');
});

jsFiddle.

Without jQuery

Array.forEach(document.getElementsByTagName('img'), function(img) {
    img.addEventListener('error', function() {
        this.style.border = '5px solid red';
    }, false);
});

jsFiddle.

The without jQuery example uses some methods not available in older IEs. You can shim these methods or use more compatible techniques.

like image 198
alex Avatar answered Sep 19 '22 17:09

alex