Monday, May 16, 2005

Debugging Javascript

Debugging Javascript has its own set of challenges; often aggrevated by a lengthy build/deploy cycle time. With the increased usage of asynchronous server calls (now with the fancy buzz word, Ajax), life has become a few notches more difficult. We still have the tried and tested alert pop-ups, And there are Javascript debuggers where one can step through the code line by line.
Alas, with a cascade of asynchrous actions, you are quickly lost. Timing and sequence matters, and your debugging tools freeze the action and most likely disturb the very events you are trying to understand. In situations like this, it is helpful to write to a log that you can inspect when things have calmed down. Some time back, I recall seeing a little utility that allowed you to write to a scrolling window on the page. I no longer have a refernce to that article, so I spent last Saturday creating my own little utility.
The concept is simple; a simple function ( called debug() ) writes to the window. If the window doesn't exist, it gets created on-the-fly. Each call to debug adds a new paragraph to the window -- I used an iframe to save me some hassle with selects shining through on IE.

var box = document.createElement ('iframe');

That gets appended to the body element. Inside (this.iframe.contentWindow;) I create a container <div>. I add the text, wrapped in a paragraph element.

var p = this.doc.createElement ('p');
p.appendChild (this.doc.createTextNode (text));
this.container.insertBefore (p, top);

All formatting is done by setting styles directly on the javascript objects; no need for an external stylesheet. To add a little finesse, I resize the window (up to a certain maximum height. After that, the iframe body takes car of the scrolling for me. I highlight the most recent paragraph and all debug text are prefixed with time [hh:mm:ss]. As the final touch, I set the opacity to 0,75 so the underlying shines through. That's it. Life just became a little simpler.
Category: Programming,Javascript

0 Comments:

Post a Comment

<< Home