Sunday, March 1, 2009

onError: Handling "Image Not Found" in JavaScript

HTTP requests are expensive, so making an HTTP request and getting a useless response (ie. 404 Not Found) is totally unnecessary and will slow down the user experience without any benefit. Even worse is when the link to an external JavaScript is wrong and the result is a 404. First, this download will block parallel downloads. Next the browser may try to parse the 404 response body as if it were JavaScript code, trying to find something usable in it.

Although, we cann't reduce the http requests if image is not found, but error can be handled resulting in showing some other appropriate image to the user.
We can use "try... catch" statement to catch the error in a web page. Alternatively, we can use the onerror event as well for the same purpose.
The onerror event is fired whenever there is a script error in the page.

Example use:
To use the onerror event, you must create a function to handle the errors. Then you call the function with the onerror event handler. The event handler is called with three arguments: msg (error message), url (the url of the page that caused the error) and line (the line where the error occurred).

onerror = handleErr

function handleErr(msg,url,l) {
//Handle the error here
return true or false
}

An another example for handling it, another image can we shown if image is not found
eg. <img src="http://www.yahoo.com/badimage.gif" alt="Bad Image" onError="this.src='http://l.yimg.com/a/i/ww/beta/y3.gif';" />

No comments:

LinkWithin

Related Posts with Thumbnails