-
Image onload and taking action if image fails to load
In one of our projects backend was sometimes returning a bad url for an image and we wanted a javascript way to detect if image url is good or not. (without making another request). I had a javascript function that was detecting if a particular image on the page is fully loaded or not. If it fails to load I wanted to replace it with a default image. For this I was checking expected image width and height when onContentReady event fires on the image wrapper. However, the problem with that approach was YUI onContentReady doesn’t really check if images inside the given element have loaded fully or not. Because of this, if the image takes longer to load, it was getting replaced with a default image even though the image url was good. To solve this I decided to use an onload event on the image element (instead of onContentReady on the wrapper). The problem with the second approach is that, if the image url is bad, onload event on the image element never fires and I wasn’t really able to replace the image with default one. I ended up using onload event on the window. When that fires, function tests for the expected height & width and if the image height & width is not correct then it replaces it with the default image.
Monthly Archive
Hi, I am Manish Ranade. I am ex-Yahoo! and currently work at Netflix as a Senior UI Engineer.