Sunday, January 29, 2012

Handling broken images with jQuery

Sometimes we deal with images that we do not have control over. I had come across some issue with broken images where images where coming from a webservice whose urls where pointing to images that did not even existed, which I think it is unpleasant to show broken images on website's.
Well one could do is use code behind to check each image status, the one that returns 404 would mean that do not exist. But when you are dealing with over hundred's of images and you must return your images on time, that would not be a good idea.
Below is an example:

Wait, what if I use jQuery to replace image src in DOM




<script type="text/javascript">

        $(document).ready(function () {
            $("img").error(function () {
                $(this).unbind("error").attr("src", "Images/noimage.png");
            });
        });
   
</script>

Summary what the above jQuery script does:

When the page load completes, get all image tags that have returned error event (broken images return an error), then unbind the error event and replace the “src” of the image with "Images/noimage.png"
Now I got nice and clean image… 


Happy Query...

Friday, January 27, 2012

Jquery CDN Comparison

Jquery CDN (Fastest on Average)
Microsoft CDN (Fastest in Europe)
Google CDN (Most Popular)

Pingdom.com did a neat little analysis to figure this out, and it emerged that the jQuery.com CDN (aka Edgecast) delivers jQuery fastest on average, with the Microsoft CDN coming in second, and the Google CDN finishing third. In Europe, the Microsoft CDN delivered fastest of all.

Source: