Things I didn’t Know about Chrome DevTools

Posted on

I have been using Firebug as my debugging tool since I started web development. Firebug has been very helpful and the one thing I knew Chrome DevTools has that Firebug doesn’t is performance profiling which helps finding signs of memory leaks on a web page. I have wanted to take the free course Explore and Master Chrome DevTools for a while and I finally cross it out of my to-do list. It took me about four hours to complete the course and I have learned a few cool features of Chrome DevTools that I didn’t know about.

Explore and Master DevTools

  • Ways of get a DOM node
    Besides using the magnifier to select the DOM node on the web page, you can use the jQuery style of getting the DOM node with “$” sign. For example, $(“#name”) will give you the DOM node with id as name. If you select a DOM node in the Elements tab, you can then type in “$0″ in the Console tab to get the DOM node. On the other hand, you can type “inspect($0)” in the Console tab to show the DOM node in the Element tab.
  • Show style for different states
    lunapic_136720788190059_6There is a Toggle Element States option in the Elements -> Styles tab which will open the section for you to set the element state to active, focus, hover, and visited. I found this very helpful to debug the style issue for these states as the style definitions won’t be shown in the Styles tab unless they are in that state.
  • Dynamical editing source files and data source and view the change history
    You can edit CSS files or JavaScript files under the Sources tab. Right click in the file, you will see the option “Local modifications…” to see the change history and revert them. While we are used to editing CSS files, dynamically being able to update JavaScript is very useful.
  • Save updated file locally
    The changes were saved in the Chrome local storage if you edit them in the Sources tab and you can also save the updated files in your computer and override the original ones.
  • Events/Frames view in Timeline
    Frames view in Timeline
    The Timeline tab provides three types of views for the recording: Events, Frames, and Memory. The Events/Frames view shows the time spent on HTML parsing(blue), JavaScript rendering(yellow), style calculation(purple), and CSS rendering(green). The memory view is for detecting the sign of memory leaks.
  • Other plugins
    Page speed: It’s similar to YSlow. It gives you the suggestions of improving performance. After it’s installed, it’s will be shown as a new tab in the devTools.
    Google Closure: Compress multiple JavaScript files into one to reduce the number of HTTP requests.

Above are just new things that I learned in the class and I enjoyed taking this interactive class. Visit this link for more details about how to improve the performance of your application with Chrome DevTools.


JavaScript Memory Leaks

Posted on

1. What is memory leak?
Memory leak refers to memory allocated for the application which is unable to be reallocated even after it’s not being used. Normally, garbage collectors collect the DOM elements and event handlers when they are not referenced or unreachable. However, memory leaks are unforgiving for earlier versions of IE, IE 7 and before, because the memory manager does not understand the JavaScript cycle and will not reclaim the memory until the cycles are broken explicitly which can be done by assigning to null.

2. Why do you need to be aware?
Memory leak is a common unintentional programming mistake in large web applications. Memory leaks reduce the performance of a web application until it becomes unusable when the wasted memory grows beyond what the system can afford. As a web developer, developing a web application to meet the functional requirements is just the first step, performance requirements are as important for the success of a web application, not to mention the possible failure of the application or a browser crash.

3. What are the major causes for memory leak in JavaScript?
1) Circular References
A simple example is a DOM object which is referred by a JavaScript object and at the same time is referring to the same or another JavaScript object, this DOM object may cause memory leak. The reference of the DOM object won’t be collected by garbage collector even after the script stops. This pattern usually happens with a chain of object references and it’s hard to detect. To beak the circular reference, either the object referencing the DOM object or the reference of the DOM object needs to be assigned as null.

2) JavaScript Closure
Because of the limitation of the JavaScript scope, a lot of implementations rely on the JavaScript closure. Please check out my previous blog post JavaScript Scope and Closure if you want to know more about closures.

Closure can cause memory leak because the inner function holds a reference to the outer function’s variables so the inner function can continually access private variables defined in the outer function even after the function has returned. It is the best practice for JavaScript programmer to disconnect all the event handlers before the page unloads.

3) DOM Insertion Order
A temporary object is created whenever two DOM objects with different scopes attached together. When the DOM objects changes the scope to document, the temporary object is trapped. With that said, DOM objects should be attached in the order from the current existing DOM element on the page top down to the rest of the DOM objects so they will always share the document scope and no temporary objects are created.

4. How to detect?
Memory leaks are usually hard to detect for developer because they are caused by some unintentional mistakes within large amount of code and it doesn’t affect the functionality of the application until the memory starvation occurs in the system. It is why there is performance testing when performance metrics of the application are collected during a long term testing period.

The simplest way to detect memory leak is to check the memory usage with task manager. Open the application in a separate tab in chrome and check if the memory usage keeps going up as time passes. There are other debugging tools providing memory monitor feature such as Chrome Developer Tools. Here is a tutorial in Google Developers on the Heap Profiling feature.

References:
1. http://javascript.crockford.com/memory/leak.html
2. http://msdn.microsoft.com/en-us/library/Bb250448
3. http://www.ibm.com/developerworks/web/library/wa-memleak/


JavaScript Scope and Closure

Posted on

Remember this: In JavaScript, only function creates scope but the visibility and the life cycle of the variables are not limited to the function definition.

A local variables is created with keyword “var” and it lives within the function scope. They are private variables because they can not be accessed directly outside the function the scope but can be accessed by privileged methods – inner functions of the object.

Variables which are referred by keyword “this” are considered as public variables because they can be accessed through the object. The keyword “this” is not optional because JavaScript will only evaluate it as a local variable name without “this”. Global variables are those defined outside any function and they should be avoided.

The other fundamental concept which needs to be emphasized is that JavaScript is prototype-based inheritance and not class-based. The object definition is defined with prototype and it can be changed anytime as it needs. An instance is usually created with keyword “new” and it gets a reference to the prototype, which means it will get the updated prototype even if the change is made to the prototype chain after the creation of the instance. While prototype can manipulate all the properties associated with the object, private variables are not visible to the prototype methods.

Below is a simple example to illustrate the scope of different variables as well as the prototype concept.


function Cat(name, age) {
    this.age = age;
    
    // add a privileged method
    this.description = function() {
        this.id ? this.id++ : this.id=1;
        console.log("name = " + name,", age = "+this.age, ", version = ", this.id); 
    }
}

var myCat = new Cat("Kitty", 3);
myCat.description(); // name = "Kitty", age = 3, version = 1
    
// add a new method
Cat.prototype.setAge = function(newAge) {
    this.age = newAge;
};
    
myCat.setAge(4);
myCat.description(); // name = "Kitty", age = 4, version = 2

var myOtherCat = new Cat("Lily", 5);
myOtherCat.description(); // name = "Lily", age = 5, version = 1

You can also create the Cat object with “var Cat = { name: “Kitty”, age: … };”. As you see, you can not pass in the parameters in this case and all the properties within are public variables.

The other factor affects the JavaScript scope is the closure. JavaScript closure is the inner function can access the parameters and variables after the outer function is returned. Closure is basically a way to manipulate local variables with the return of an inner function which accesses local variables. Below is an example:


function Cat() {
    var name = "Kitty";
    var age = "1";
    this.version = 1;

    var setAge = function(newAge){
       age = newAge;
       console.log(age);
       //this.version is undefined here
    };

    return setAge;
}

var myCat = new Cat();   // myCat is the function setAge 
console.log(myCat(2));   // 2
console.log(myCat(3));   // 3