A Week in JavaScript Patterns: Load Time Configuration

Load time configuration is the process where a JavaScript application configures itself as it is being loaded. This pattern is most commonly found in libraries in which they configure themselves at load time to be optimized for a particular browser.

Load time configuration is also known as load time branching.

Motivation

The primary motivation behind load time configuration is to optimize conditional operations such as generating XMLHttpRequest instances or adding event listeners. Since both operations vary amongst clients, specific conditions must be checked before proceeding. The load time configuration pattern runs once at load time and sets the resulting value so that it doesn’t need to be checked again.

Implementation

The most common technique for implementing load time configuration is by way of a Self-invoking function which returns the correctly configured value.

The example below demonstrates how load time configuration can be used to normalize getting an XMLHttpRequest object.

var getXHR = (function () {
    if (window.XMLHttpRequest) {
        return function () {
            return new XMLHttpRequest;
        }
    }
    else if (window.ActiveXObject) {
        return function () {
            /* Msxml2 and Msxml3 checkes have been omitted
             * for simplicity's sake */
            return new ActiveXObject('Microsoft.XMLHTTP');
        }
    }
})();

First, a getXHR variable is declared and it’s value is being assigned by the self-invoking function that follows. Upon execution, a conditional is run which determines the correct method of obtaining an XMLHttpRequest object. When a match is found, a wrapper function is returned and stored as the value for getXHR variable.

Conclusion

The load time conditional pattern is used to configure a conditional value at load time. The result is a fully optimized value, specific to the the environment in which it is to be used.

Posts in this Series

This entry was posted on Monday, August 18th, 2008 at 9:12 pm and is filed under Code, Design Patterns, JavaScript. You can leave a response, or trackback from your own site.

One Response to A Week in JavaScript Patterns: Load Time Configuration

A Week in JavaScript Patterns: Self-invocation :: Love Mike G.:

On August 18th, 2008 at 9:20 pm #

[...] Load Time Configuration [...]

What do you have to say?

Site Stuff

Pages

Projects

Archives

Categories