Check if images exist before rendering with Javascript and jQuery

Check if images exist before rendering with Javascript and jQuery

Recently I ran into a problem where I was making a bunch of Facebook Graph API requests for Facebook Events in order to build an Events widget. Problem was, after receiving data from the API, some Event objects had a image urls that didn’t resolve. My fix was to check each image url, see if it resolves, and if it doesn’t replace it with a default image. Last, after all images have been checked render the Events mark up that is built with the Events data.

Because I wanted to check and replace all the image urls before rendering the Events markup, I had to set up some sort of asynchronous system to check all the images url resolution. In a nut shell the algorithm goes

  1. Gather all Image urls and make requests for them.
  2. When all Image requests return check which result in 404s
  3. Replace 404 images with default images
  4. Generating Events mark up and add it to the page.

jQuery Deferreds to the rescue.

Considering I have a bunch of Facebook Events jSon in eventsData.

Make a load image function

//make an deferred array to store a jQuery deferred for every image request
var deferreds = [];
//make a load image function that takes the event index and event image url
var loadImage = function( i, src ){
                    imgDeff = new $.Deferred();	 
		    deferreds.push( imgDeff);
		    //make an image and set up load callbacks 
		    var img = new Image();
		    img.onload = function() { 
			            console.log("I exist")
				    deferreds[i].resolve( i,src,"exsist" )
		    img.onerror = function() { 
				    console.log("I don't exist)
                                    //image doesn't exist so replace it with a default image in this case the FB user image[i] = "//"[i]"picture";
				    deferreds[i].resolve( i,src,"noexsist" );
		    //apply img
                    img.src = src;
    }//end loadImage
//loop through the events Data
var i = 0;
    loadImage( i, );
//when all the deferreds are resolved add the markup to the page
$.when.apply($,deferreds).done( function(data){ 
    //at this point eventsData has urls that will all resolve so build the markup and render
This entry was posted in Uncategorized. Bookmark the permalink.