How to detect on-page 404 errors using JavaScript?

Santoo picture Santoo · Dec 14, 2011 · Viewed 48k times · Source

I have an HTML page where several JavaScript, CSS and images files are referenced. These references are dynamically injected and user can manually copy the HTML page and the support files to another machine.

If some JS or CSS are missing, the browser complains in the console. For example:

Error GET file:///E:/SSC_Temp/html_005/temp/Support/jquery.js

I need somehow these errors reported back to me on the inline JavaScript of the HTML page so I can ask user to first verify that support files are copied correctly.

There's the window.onerror event which just inform me that there's a JS error on the page such as an Unexpected Syntax error, but this doesn't fire in the event of a 404 Not Found error. I want to check for this condition in case of any resource type, including CSS, JS, and images.

I do not like to use jQuery AJAX to verify that file physically exists - the I/O overhead is expensive for every page load.

The error report has to contain the name of the file missing so I can check if the file is core or optional.

Any Ideas?

Answer

Alexander O'Mara picture Alexander O'Mara · Feb 27, 2015

To capture all error events on the page, you can use addEventListener with the useCapture argument set to true. The reason window.onerror will not do this is because it uses the bubble event phase, and the error events you want to capture do not bubble.

If you add the following script to your HTML before you load any external content, you should be able to capture all the error events, even when loading offline.

<script type="text/javascript">
window.addEventListener('error', function(e) {
    console.log(e);
}, true);
</script>

You can access the element that caused the error through e.target. For example, if you want to know what file did not load on an img tag, you can use e.target.src to get the URL that failed to load.

NOTE: This technically will not detect the error code, it detects if the image failed to load, as it technically behaves the same regardless of the status code. Depending on your setup this would probably be enough, but for example if a 404 is returned with a valid image it will not trigger an error event.