Branching JavaScript for Different Browsers

I’ve been reading Pro JavaScript Design Patterns and I just got to try out a neat technique for dealing with the lexical differences between different browsers’ (I’m looking at you, IE) JavaScript implementations. The branching pattern allows you to create classes that execute different code based on whatever conditions you choose to examine.

/**
 * @constructor General miscellaneous utilities.
 */
mySingleton.etc = function () {
    /**
     * Branching object to handle both standard and 
     * Microsoft DOM interfaces.
     */
    var standard = {
            /**
             * Use the classList (standard) object.
             */
            getClassCount: function (element) {
                return element.classList.length;
            }
    }, 
    ie = {
            /**
             * Use the className (IE) object.
             */
            getClassCount: function (element) {
                return element.className.length;
            }
    }, 
    testObject, 
    testElement;

    testElement = document.createElement("body");

    try {
        testObject = webkit.getClassCount(testElement);
        return standard;
    } catch (e) {
        testObject = ie.getClassCount(testElement);
        return ie;
    }

};

It’s fairly easy to see what’s transpiring here. We basically have two cases we have to handle: IE and everything else. So we add two respective private members to this class, “standard” and “ie”. Then we check to see which method the class should return. We do this by asking the browsers to execute the code in question. Then we return the private member that can contains the code to be executed.

Simple, right?

Published by

Tom Cornyn

I'm just a regular guy. I eat tires.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s