JavaScript debug is a very troublesome thing in web application development. Because many web browsers will not notify you if there is any error in the JavaScript codes you write. They just silently fail and block the following codes execution. In order to debug JavaScript codes, we need a good log mechanism which will help us log the error information,, we often need to log errors in JavaScript codes to server for debug purpose in a production web application,
What should we do?
The first thought comes into our mind may be using AJAX, since it involves client server communication and we also should make it asynchronously because we don't want to interrupt users while we are logging something to server. This is feasible, but it needs many codes to be written to create the XMLHttpRequest object and implements some function related to it, it is also error prone since the communication may be interrupted as well.
Is there any simple and reliable way? Yes, we can create an Image object in our JavaScript. The details steps are:
1. We need to create a backend server script to get the passed query strings and store them on the server. We assume it is logger.php here;
2. Create a log() function in JavaScript:
function log(type,message){
var img=new Image();
img.src="logger.php?type="+type+"&message="+message;
}
3. Call the log() function like :
log("Error","Syntax error");
That's all. You can simply log information to server now.
In the log() function, we created an Image object, it is supported in all modern browsers, later when we assign the src property, the image will be loaded immediately. this will load the logger.php script with the passed query string. It has similar effect as the AJAX method.
According to "Professional JavaScript for Web Developers", the benefits for using this are:
- The Image object is available in all browsers, even those that don’t support the XMLHttpRequest object.
- Cross-domain restrictions don’t apply. Often there is one server responsible for handling error logging from multiple servers, and XMLHttpRequest would not work in that situation.
- There’s less of a chance that an error will occur in the process of logging the error. Most Ajax communication is handled through functionality wrappers provided by JavaScript libraries. If that library’s code fails, and you’re trying to use it to log the error, the message may never get logged.