Main Page

Image loading errors

Image loading errors
The
window
object isn’t the only one that supports the
onerror
event handler; images do too. When
an image fails to load for any reason (for example, the file does not exist), the
error
event fires on the
images. You can set the
onerror
event handler for an image either in HTML or through script. For
example:
<html>
<head>
<title>Image Error Test</title>
</head>
<body>
<p>The image below attempts to load a file that doesn’t exist.</p>
<img src=”blue.gif”
onerror=”alert(‘An error occurred loading the image.’)” />
</body>
</html>
This example assigns the
onerror
event handler directly in the HTML. Because the image
“blue.gif”
doesn’t exist, the alert is displayed letting the user know the image didn’t load completely. In order to
assign the event handler using a script, you must wait until after the page has loaded before setting the
image’s
src
attribute:
<html>
<head>
<title>Image Error Test</title>
<script type=”text/javascript”>
function handleLoad() {
document.images[0].onerror = function () {
alert(“An error occurred loading the image.”);
};
document.images[0].src = “blue.gif”;
}
</script>
</head>
<body onload=”handleLoad()”>
<p>The image below attempts to load a file that doesn’t exist.</p>
<img />
</body>
</html>
In this example, the first image isn’t assigned an
src
attribute in the HTML. When the page is loaded,
however, the image is first assigned an
onerror
event handler and then has its
src
property set to
“blue.gif”
, which doesn’t exist. The alert displays once again, indicating the image didn’t load.
Unlike the
onerror
event handler for the window object, the image’s
onerror
event
handler doesn’t pass any arguments for extra information.
421
Error Handling
17_579088 ch14.qxd 3/28/05 11:41 AM Page 421


JavaScript EditorFree JavaScript Editor     Ajax Editor


©