Tuesday, November 06, 2007

Firebug for debugging Javascrpt - turn it off in Production

The Firebug and Web Developer plugins for Firefox are simply awe-inspiring. Using these two, I was able to show my page as it should look when printed (it had separate print media css) - Web Developer - and then use Firebug to dynamically update the CSS until I was happy with it.

Firebug lets you examine DOM, HTML, Scripts and Net statistics. The Developer Toolbar lets you take apart and examine your page in various funky ways. There is a lot in common between Firebug and the Developer Toolbar.

On IE, MS Developer Toolbar gives you some of these capabilities too, and I use it a lot.

One of the most useful features of Firebug is the Console API. It gives a small collection of files you put into your web app, and then you can log messages from Javascript - so much more powerful that using alert() calls or the status bar.

You can print out logging messages:

console.log("message");
console.debug("message");
console.warn("message");
console.error("message");

And there are more complicated uses like:

console.dir(object);

This prints an interactive listing of all properties of the object. This looks identical to the view that you would see in the DOM tab (in Firebug).

Or how about:

console.dirxml(node)

This prints the XML source tree of an HTML or XML element. This looks identical to the view that you would see in the HTML tab. You can click on any node to inspect it in the HTML tab (in Firebug).

Press F12 to show the console. Once you see the console, you can also enter any of the above commands in the command line shown.

You would generally use Firebug for debugging during some development stage and would remove the various console statements before migrating forwards. It is easy to forget this though, and find you have let code go into Production with a few console statements left in. I use the following JSP to import Firebug. This uses firebug.js if I am doing local development - i.e. accessing the page using "localhost". It uses firebugx.js for other environments - i.e. when the environment is accessed through proper host name - which provides versions of all calls that do nothing.

<% if (request.getServerName().equals("localhost")) { %>
  <script type="text/javascript" src="<%=request.getContextPath()%>/include/firebug/firebug.js"></script>
<% } else { %>
  <script type="text/javascript" src="<%=request.getContextPath()%>/include/firebug/firebugx.js"></script>
<% } %>

No comments: