Firebug Tutorial – Logging, Profiling and CommandLine (Part II)

Firebug Tutorial

Section 1: Console Tab : Logging, Profiling and CommandLine (Part II)

Introduction

This tutorial is the part II of “Firebug Tutorial – Logging, Profiling and CommandLine“. (If you haven’t read the part I of this tutorial, I would recommend you to read the part 1 first.)

The following topic will be covered in this section.

  • Javascript Profiler
  • Tracing error
  • Tracing XmlHttpRequest object

#1. Javascript Profiler

Javascript Profiler is very useful feature of Firebug for measuring the execution time of each javascript code. It is useful for improving the performance of your code or if you wanna find out why a particular function takes soooo long. It is a bit similar to console.time() that I mentioned already to previous part but Javascript Profiler can give you more detailed information about what’s happening with your code.

There are three ways to use Javascript Profiler. You can call this function by clicking “Profile” button on the toolbar of Firebug console or through code “console.profile()” or by typing “profile()” in commandline. I will cover first two in this tutorial but not for using profile() in commandline. If you want to know how to use it in commandline, please check-out this article.

console.profile()

  • Copy and paste the code in notepad and then, save as a htm file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Firebug</title>
<script language="javascript" type="text/javascript">

function startDoSomething(){
<strong>console.profile('Measuring time');</strong>
doSomething();
<strong>console.profileEnd();</strong>
}
function doSomething(){
doThis(1000);
doThis(100000);
doThat(10000);
doThisAndThat(1000,10000);

}
function doThis(count){
for(var i=0;i&lt;count;i++){}
}

function doThat(count){
for(var i=0;i&lt;count;i++){}
}

function doThisAndThat(countThis,countThat){
for(var i=0;i&lt;countThis;i++){ for(var j=0;j&lt;countThat;j++){} }
}
</script>
</head>
<body>
Open the console tab. Click the button below and wait a lit.. <br />
<input type="button" value="Start" onclick="startDoSomething();"/>
</body>
</html>
  • Open this file in Firefox browser.
  • Open the Console tab on Firebug console.
  • Click “Start” button and wait a lit.. (You will get the result like the screenshot below. )

profiler.jpg

(The list is sorted based on the execution time.)

Columns and Description of Profiler

  • Function column : It show the name of each function.
  • Call column : It shows the count of how many a particular function has been invoked. (2 times for doThis() function in our case. )
  • Percent column : It shows the time consuming of each function in percentage.
  • Own Time column : It shows the duration of own script in a particular function. For example: doSomething() function has no its own code. Instead, it is just calling other functions. So, its own execution time will be 0ms as shown in picture. If you wanna see some values for that column, add some looping in this function.
  • Time column : It shows the duration of execution from start point of a function to the end point of a function. For example: doSomething() has no code. So, its own execution time is 0 ms but we call other functions in that function. So, the total execution time of other functions is 923 ms. So, it shows 923 ms in that column. Not clear? Feel free to let me know. I can try once more.. I don’t mind to explain you again. (That’s my problem in writing .. I can’t write very clear.. Sorry about that. )
  • Avg column : It shows the average execution time of a particular function. If you are calling a function one time only, you won’t see the differences. If you are calling more than one time, you will see the differences. Take a look the doThis() function at second line of picture above.
    The formula for that column is ~
    Avg = Own Ttime / Call;
  • Min column and Max column: It shows the minimum execution time of a particular function. In our example, we call doThis() function twice. When we passed 1000 as an parameter, it probably took only a few millisecond. (let’s say 1 ms.). then, we passed 100000 to that function again. It took much longer than first time. (let’s say 50 ms.) . So, in that case, “1 ms” will be shown in Min column and “50 ms” will be shown in Max column.
  • File column : the file name of file where the function located.

Note: You can set the title of profiler by passing one string to console.profile() function. In our example (console.profile(‘Measuring time’);), ‘Measuring time’ is the title of profiler.
Profiler button from Console tab’s toolbar

If you don’t want to profile thru the code, you can use “Profile” button from the toolbar of Firebug console.

toolbar-console.jpg

In order to test this,

  • you need to remove two lines (console.profile(‘Measuring time’); and console.profileEnd();) from doSomething() function.
  • Open this file in Firefox.
  • Open Console tab of Firebug console.
  • Click “Profile” button ( right button on the toolbar of Firebug console.)
  • Click “Start” button on your page.
  • Wait for 1 min ( or a lit less than that.)
  • Click “Profile” button again. ( You will get the same graph as the picture above.)

That’s all about Javascript Profiler. Let me know if you have any question or comment.

Okay. Let’s move on to next topic.

#2. Options of Console tab

There is one link called “Options” at the right-side of Firebug console. If you click this link, you will see the menu as shown in picture below.

menu-of-console-tab.jpg

I will divided those times in three categories.

  1. Errors Tracing
    1. Show Javascript Error
    2. Show Javascript Warnings
    3. Show CSS Errors
    4. Show XML Errors
  2. XmlHttpRequest Tracing
    1. Show XMLHttpRequests
  3. CommandLine
    1. Larger Command Line

#2.1 Errors Tracing and Filtering

  • Show Javascript Errors
  • Show Javascript Warning
  • Show CSS Errors
  • Show XML Errors

Those options are used for tracing the errors of your script, style sheet and XML. You can also filter the error messages based on the type of error that you wanna.

Example Code


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Firebug</title>
<style type="text/css">
.normalText{
bcolor : red;  /* This is ERROR!! */
}
</style>
<script language="javascript" type="text/javascript">
function foo(){
var objTxt = doucmnet.getElementById('nameTextBox');  //This is ERROR!!
alert(objTxt.value);
}
</script>
</head>
<body>

<input id="nameTextBox" class="normalText" type="text" />
<input type="button" value="Start" onclick="foo();"/>
</body>
</html>

Output ~

error.jpg

  • Copy and paste the code in notepage.
  • Save as a .htm file.
  • Check “Shows Javascript errors” and “Shows CSS errors” on Console tab.
  • Reload the page
  • First, you will get the CSS error. ( Reason : We wrote bcolor instead of color in “normalText” class. )
  • Click the button
  • then, we will get the another error. ( because we wrote “doucmnet” instead of “document” in the code. )

I think those options are very sample to use. If you wanna see the errors, just check the option in menu. then, Firebug will give very good information about the errors that you are getting. Uncheck it if you don’t want.

#2.2. Tracing XmlHttpRequest object

This is also one of the most popular feature of Firebug and it is really helpful for Ajax developer. The problem with Ajax is that it is very difficult to figure out if something goes wrong in XmlHttpRequest. Sometimes, you have no idea about what’s going on behind the sense while the indicator keep on cycling all the time. One of the problem that I face when I was playing around with ajax, it is difficult to find out whether the response format from Web service are correct or not.

but things are very simple with Firebug. You only need to select “Show XmlHttpRequest” option. Firebug will tell the following thing.

  1. The execution time
  2. Parameters (QueryString)
  3. HTTP Header
  4. Response

Example : I used Yahoo UI DataTable in this sample. This sample is the updated version of this sample from Yahoo UI.

Download : SourceCode

  • Download the zip file from the link above
  • Extract the zip file and put all files to PHP directory.
  • Try to call this file “dt_xhrlocalxml_clean.html” from Firefox ( http://localhost/yui-php/dt_xhrlocalxml_clean.html in my case.)
  • Open the Console tab in Firebug console.
  • Select “Show XmlHttpRequests” option
  • Click the button “Load Data” on the page
  • The following result as shown in picture will be shown. (The style might be a lit bit different since I didn’t change the path in some CSS files. )

datatable.jpg

  • And check the Console tab in Firebug console.
  • You will the detailed response in XML format as shown in the picture below.

httprequest.jpg

Note: If you don’t wanna download or if you don’t have PHP installed on your machine, you may try to check this online sample from Yahoo. But there won’t be any button so you should select the “Show XmlHttpRequests” option first and reload or open the link…

Okay. That’s all for today. I was thinking to write about CommandLine in this part but I don’t have the enough time to write it today. Don’t worry. I will tell about CommandLine tomorrow.

Cya. Don’t hesitate to drop a comment if you have any suggestion or comment. I appreciate it.

Firebug Tutorial – Logging, Profiling and CommandLine (Part I)

Firebug Tutorial

Section 1: Console Tab : Logging, Profiling and CommandLine (Part II)

Overview of Console Tab

This tab is mainly used for logging. It also can be used as CommandLine window (like immediate window in Microsoft Visual Studio) while you are debugging the Javascript. It can be used for monitoring the execution of Javascript code by using Profiling service.

The following topic will be covered in this section.

  • Logging in Firebug (with String Substitution pattern )
  • Grouping the logs or messages
  • console.dir and console.dirxml
  • Assertion ( console.assert() )
  • Tracing ( console.trace() )
  • Timing ( Measuring the time of your code)
  • Javascript Profiler (An introduction in this tutorial, the details will be covered in next tutorial.)

#1. Logging in Firebug

Firebug supports logging in Console tab. So, you don’t need to use alert(‘something’) or document.write(‘something’) anymore.

There are five types of logging in Firebug.

  • console.log : Write a message without icon.
  • console.debug : Writes a message to the console, including a hyperlink to the line where it was called
  • erroricon.png console.error() : Writes a message to the console with the visual “error” icon and color coding and a hyperlink to the line where it was called.
  • infoicon.png console.info() : Writes a message to the console with the visual “info” icon and color coding and a hyperlink to the line where it was called.
  • warningicon.png console.warn() : Writes a message to the console with the visual “warning” icon and color coding and a hyperlink to the line where it was called.

Example Code:

  • Open the htm file called “Plain HTML” or create one HTML file.
  • Paste the following code with <body> tag.
<script language="javascript" type="text/javascript">
console.log('This is log message');
console.debug('This is debug message');
console.error('This is error message');
console.info('This is info message');
console.warn('This is warning message');
</script>

You will get the following output. If you click on hyperlink (“test.htm” in this case), it will take you to script tab and will highlight the line that wrote this message.

basic-logging-concept.jpg

String Substitution Patterns

String substitution parterns can be used in console.log, console.info, console.debug, console.warn and console.error . You can use the same way that we used in C/C++.

%s String
%d, %i Integer (numeric formatting is not yet supported)
%f Floating point number (numeric formatting is not yet supported)
%o Object hyperlink

Example :

Note: I will use console.log in the example below even all console objects (console.log, console.info, console.debug, console.warn and console.error ) support string substitution.

  • Remove “script” tag that we pasted for the previous example.
  • Paste the code below within <body> tag.
<script language="javascript" type="text/javascript">

//This is for normal string substitution " %s, %d, %i, %f".
console.log("My Name is <strong>%s</strong>. My Date of Birth is <strong>%dth %s, %i</strong>. My height is <strong>%f</strong> m.", "Nicolas Cage", 7, 'January', 1964, 1.8542);

function Foo(){
this.LeftHand = function(){
return "Left Hand";
}
this.RightHand = function(){
return "Right Hand";
}
}

//This is for object "%o".
var objFoo = new Foo();
console.log('This is <strong>%o</strong> of Foo class.', objFoo);

</script>

console-string-substitution1.jpg

If you are using %o in your log, the object will be shown as a hyperlink in green color. This hyperlink is linked to the DOM tab. So, If you click “object” in second line, you will see the list of properties of that object (LeftHand and RightHand in this case.)

#2. Grouping

Firebug allows you to group the message or log in Console tab. If you have some many logs in your code, you can probably divide your log into small group or subgroup

Example ~

<script language="javascript" type="text/javascript">

var groupname = 'group1';
console.group("message group : %s " , groupname);
console.log("log message 1 from %s", groupname);
console.log("log message 2 from %s", groupname);
console.log("log message 3 from %s", groupname);
console.groupEnd();

groupname = 'group2';
console.group("message group : %s " , groupname);
console.log("log message 1 from %s", groupname);

var subgroupname = 'subgroup1';
console.group("message group : %s " , subgroupname);
console.log("log message 1 from %s", subgroupname);
console.log("log message 2 from %s", subgroupname);
console.log("log message 3 from %s", subgroupname);
console.groupEnd();

console.log("log message 3 from %s", groupname);
console.groupEnd();

</script>

group-message.jpg

#3. console.dir and console.dirxml

  • console.dir : It can be used for getting all properties and methods of a particular object. According the example below, we can get the Model (property) and getManufactor (method) of Car object by using console.dir(); You can also pass the object of HTML element (eg: console.dir(document.getElementById(‘tbl1’)); ) instead of objCar and let’s see the result. (You will get all properties and methods of the HTML table called “tbl1”).
  • console.dirxml : print the XML source tree of HTML element.
<table id="tbl1" cellpadding="0" cellspacing="0" border="0">
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
</table>
<script language="javascript" type="text/javascript">
//Create a class
function Car(){
this.Model = "Old Model";

this.getManufactor = new function(){
return "Toyota";
}
}

//Create a object
var objCar = new Car();

//Firebug
console.dir(objCar);
console.dirxml(document.getElementById('tbl1'));

</script>

console-dir.jpg

#4. Assertion ( console.assert() )

You can use console.assert() to test whether an expression is true or not. If the expression is false, it will write a message to the console and throw an exception.

Example :

<script language="javascript" type="text/javascript">
function whatIsMyAge(year){
var currYear = 2007;
return currYear - year;
}

var yearOfBirth1 = 1982;
var age1 = 25;
console.assert(whatIsMyAge(yearOfBirth1) == age1);

var yearOfBirth2 = 1982;
var age2 = 11;
console.assert(whatIsMyAge(yearOfBirth2) == age2); //You should get the error here.
</script>

assertion-failure.jpg

#5. Tracing ( console.trace() )

This function is very interesting. Before I tell you the way that I understand, let’s take a look what console.trace does exactly in official website.

console.trace()

Prints an interactive stack trace of JavaScript execution at the point where it is called.

The stack trace details the functions on the stack, as well as the values that were passed as arguments to each function. You can click each function to take you to its source in the Script tab, and click each argument value to inspect it in the DOM or HTML tabs.

This function will tell you about the route information from start point to end point. If you are not clear what I mean, let’s take a look at the sample code and the result.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Firebug</title>
<script language="javascript" type="text/javascript">
function startTrace(str){
return method1(100,200);
}
function method1(arg1,arg2){
return method2(arg1 + arg2 + 100);
}
function method2(arg1){
var var1 = arg1 / 100;
return method3(var1);
}
function method3(arg1){
console.trace();
var total = arg1 * 100;
return total;
}

</script>
</head>
<body>
<input type="button" value="Trace" onclick="startTrace('Result');"/>
</body>
</html>

trace.jpg

Suppose: we wanna know how “method3” function is invoked. So, we put this code “console.trace()” in that method. then, we run the program and we got the result as picture above. If we read the result from bottom to top, we will see “onclick(click clientX=34, clientY=26)”. That means the execution of Javascript started at on click event of button. then, we got “startTrace(“Result”)” in second line. That means startTrace function is invoked after firing onclick event and the parameter is “Result”. If we keep on checking from bottom to top, we will figure out the completed route from onclick event to method3.

If you wanna test more, you can move this code “console.trace()” to method2(). then, firebug will give the new route from onclick event which is a started point to method2() which is the end point.

I think that it’s pretty useful if you are debugging the other developer’s source code and you have no idea why this function is invoked.

Let me know if you are not clear what I’m trying to explain about console.trace();.

#6. Timing ( Measuring the time of your code)

You can use console.time(timeName) function to measure how long a particular code or function take. This feature is very helpful if you are trying to improve the performance of your Javascript code.

Example :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Firebug</title>
<script language="javascript" type="text/javascript">
function measuretheTime(){
var timeName = 'measuringTime';
console.time(timeName);

for(var i=0;i&lt;1000;i++){
///do something
for(var j=0;j&lt;100;j++){
//do another thing.
}
}

console.timeEnd(timeName);
}
</script>
</head>
<body>
<input type="button" value="Trace" onclick="measuretheTime();"/>
</body>
</html>

Result : measuringTime: 16ms

#7. Javascript Profiler

You can start the profiler thought code (console.profile(‘profileName’)) or by clicking “Profile” button from “Console” tag. It can be used for improving the performance of Javascript. It is similiar to the console.time() function but profiler can give your more advanced and detailed information.

I will tell you about this more details in next tutorial (Part2) . I hope you all are clear about this tutorial. If you have any comment or suggestion, please drop a comment.. Thanks. C ya tomorrow.

Reference ~


Firebug Tutorial – Overview of Firebug


A few words from me

It has been over 1 year that I’m using Firebug in web development. I found it very useful. I’m really thank to SangSing who introduces me about Firebug. I used to encourage a lot of my techie friends to use Firebug but they said that they don’t know how to use it. They told me that they wanna get something that include all features of firebug and examples. I googled a lit bit but I didn’t find nice resources that covers everything about firebug. So, I decided to write this tutorial. I will try to cover all features of firebug as much as I can. I will show each features with sample sourcecode and screenshot if it required. Don’t hesitate to contact me if you have any suggestion or comment.

There are 5 sections in this tutorial.

  • Section 1: Overview of Firebug : An introduction of Firebug and feature lists, how to install it and a few notes
  • Section 2: Logging, Tracing and CommandLine : Everything related to Console tab. An introduction of CommandLine windows which is the same as Immediate windows or Watch window from Visual Studio.
  • Section 3: HTML DOM Inspector and HTML CRUD operation : This section will tell you about what HTML inspecting is, how to inspect the HTML element, why it is useful and etc. I will also show you how to create/update/delete the HTML DOM dynamically in HTML tab.
  • Section 4: Javascript debugging with Firebug : This section will cover everything about javascript debugging which is the most famous feature of Firebug. It will also show you how to use Console tab while debugging the Javascript.
  • Section 5: CSS, DOM and Net Tab : (I haven’t decided whether I should write about them in one section or not. )

As I said above, I will try to cover as much as possible. If I miss out something in this tutorial, please let me know. I appreciated it.

Getting Started : Overview of Firebug

Note: I will cover some basic understanding about firebug and its features, installation and a few screenshots in this section. So, if you already have some ideas about Firebug, you may probably skip this section.

Firebug - Web Development Evolved

What is Firebug?

Firebug is one of the most popular Mozilla Firefox’s extensions (a.k.a addon). It is also a tool that make the web developers’ life easier. It includes a lot of cool features such as debugging, HTML inspecting, profiling and etc which are very useful for web development.

Features

  • Javascript debugging
  • Javascript CommandLine
  • Monitor the Javascrit Performance and XmlHttpRequest
  • Logging
  • Tracing
  • Inspect HTML and Edit HTML
  • Edit CSS

Where to get Firebug Addon?

  • Go to the official firebug website http://getfirebug.com .
  • There is the image as below at the right-side of the firebug website. Click this image to install.

Click to install Firebug

  • The following dialog will be shown after clicking the image above. Click to “Install Now” button.

Firebug - Software Installation

  • After the installation is completed, you need to restart the browser.

Screenshots

Main Menu (under “Tools” Menu)

“Firebug” and “Error Console” menu will be shown under “Tools” menu of Firefox.

firebug-menu-under-tool-menu.jpg

  • Firebug : It is just a placeholder for Firebug’s submenus.
  • Error Console : If you click this menu, one console window will be launched with the list of errors, warnings and message. Actually, this error console is the same as the console tab from Firebug console.

Firebug Menu

If you click “Firebug” menu under “Tools”, the following submenus will be shown.

firebug-menu-under-firebug-menu.jpg

  • Open Firebug : Open the firebug console within the browser. If you don’t wanna click this menu, you can simply press “F12” to open the firebug console.
  • Open Firebug in New Window : Open the firebug console in separated window.
  • Disable Firebug : It is for disabling firebug. This option is very important. You should disable the firebug if you don’t need it because If you don’t disable the firebug, it might be a lit bit slow to surf the Ajax-enabled websites like GMail.
  • Disable Firebug for **** : You can disable the specific website instead of disabling the whole firebug.
  • Allowed Sites : You can add the list of website that you want to surf with Firebug enabled option.
  • Inspect the Element : This menu is for inspecting the HTML element. Please read more about this in section 3.
  • Profile Javascript : This option is available in Firebug enabled mode only. It is used for monitoring the execution of javascript code. This option is really useful when you have performance issue with your code. Please read more about this in Section 4.
  • Clear Console : Clear the console tab of Firebug console.
  • CommandLine : Open the console tab
  • Search : Set the focus to the Search textbox of current tab.

Content Menu

There is only one menu called “Inspect Element” in content menu. This menu is very useful. Please read more about this in Section 3.

inspect-element-on-content-menu.jpg

Firebug Console

The picture below is Firebug console.

Firebug Console

It contains six tabs such as Console tab, HTML tab, CSS tab, Script tab, DOM tab and Net tab.

  • Console tab : It is for logging, profiling, tracing and commandline.
  • HTML tab : It is for inspecting HTML element, editing HTML and changing the stylesheet at runtime. CSS, Layout and DOM console are already included as the subtabs.
  • CSS tab : You can check how many css file included in the webpage easily. You can simply select the CSS file that you like and you can made the changes to that file on the fly. (I don’t use that tab that much since the same one is already included in HTML tab. )
  • Script tab : It is for debugging Javascript code. Watch and Breakpoints consoles are the subtab of Script tab.
  • DOM tab : It is for exploring DOM. (I don’t use that tab that much. Instead, I used to use DOM tab from HTML console and Script tab.)
  • Net tab : It is for monitoring network activities. It helps you to know why your page (or a particular webpage) is taking so long to load in the browser.

Status Bar

You will see the green cycle if there is no error on your page.

green-cycle-on-status-bar.jpg

You will see the red cycle and the count of errors if there is some errors in your page.

red-cycle-on-status-bar.jpg

Keyboard and Mouse Shortcuts

F12. I used to use only F12 to open/close the Firebug console.

If you wanna read the completed list of shortcuts, you can check-out here.

Problem?

Please check-out this FAQ page.

If you still have problems, you drop a comment in my blog. I will reply as soon as possible. Or you can probably contact with Firebug User Group.

Conclusion

That’s all. :) I think you now have some ideas about what firebug is, how it looks like and how to install. If you are already familiar with firebug, this section will be too plain for you since I didn’t put anything new in this section. I will tell you more details about each tab in next section. So, come back tomorrow!!

Feel free to let me know if you have any idea or comment about this tutorials. Your comment will make this tutorials better. I appreciate it.