O'Reilly logo

High Performance JavaScript by Nicholas C. Zakas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Don’t Repeat Work

One of the primary performance optimization techniques in computer science overall is work avoidance. The concept of work avoidance really means two things: don’t do work that isn’t required, and don’t repeat work that has already been completed. The first part is usually easy to identify as code is being refactored. The second part—not repeating work—is usually more difficult to identify because work may be repeated in any number of places and for any number of reasons.

Perhaps the most common type of repeated work is browser detection. A lot of code has forks based on the browser’s capabilities. Consider event handler addition and removal as an example. Typical cross-browser code for this purpose looks like the following:

function addHandler(target, eventType, handler){
    if (target.addEventListener){  //DOM2 Events
        target.addEventListener(eventType, handler, false);
    } else {   //IE
        target.attachEvent("on" + eventType, handler);
    }
}

function removeHandler(target, eventType, handler){
    if (target.removeEventListener){  //DOM2 Events
        target.removeEventListener(eventType, handler, false);
    } else {   //IE
        target.detachEvent("on" + eventType, handler);
    }
}

The code checks for DOM Level 2 Events support by testing for addEventListener() and removeEventListener(), which is supported by all modern browsers except Internet Explorer. If these methods don’t exist on the target, then IE is assumed and the IE-specific methods are used.

At first glance, these functions look fairly optimized ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required