Javascript Coding Patterns: TaskRunner

Posted on 12/27/2008 @ 06:18PM

Nowadays it's painfully clear that the browser market is overpopulated. Web developers have to make sites work in a minimum of 3 browsers and their respective sub-versions. Clients, designers and developers alike want sites to look cool, and function well, but since browser support is inconsistent, we often must sacrifice function, or leave part of our audience with a so-so user experience; neither of these makes anyone happy.

Naturally part of the answer is compromise; we can sacrifice a feature, or sacrifice a small portion of the audience - usually a bit of both. But small innovations can help us find middle ground in this area.

This brings us to a Javascript coding pattern I've been making use of lately, I call it the TaskRunner, but it probably most closely resembles Init-time branching or something similar.

The premise is this: when the page loads, do a browser type/version check, and trigger code written specifically for this user's browser. Then run any tasks for all browsers. That's it.

The code looks something like this:

 

var TaskRunner = {
    
    // Fire off all tasks
    run: function()
    {
        TaskRunner.ie6();
        TaskRunner.ie7();
        TaskRunner.allIe();
        TaskRunner.nonIe();
    },
    
    // Internet Explorer 6-specific tasks
    ie6: function()
    {
        if (!$.browser.msie || $.browser.version != 6) { return; }
    
        /*
            pngFix();
            minHeightHack();
            
            // ...
        */
    },
    
    // Internet Explorer 7-specific tasks
    ie7: function()
    {
        if (!$.browser.msie || $.browser.version != 7) { return; }
    
        /*
            ...
        */
    },
    
    // Tasks for both IE6 and IE7
    allIe: function()
    {
        if (!$.browser.msie) {return;}
        
        /*
            ...
        */
    },
    
    // Firefox/Safari/etc.
    nonIe: function()
    {
        if ($.browser.msie) { return; }
    },
    
    // This one always runs
    all: function()
    {
        // No check required
        
        /*
            doAnimation();
            loadGoogleAnalytics();
            showSwf();
            etc();
        */ 
    }  
};

// When the DOM loads, we only make one function call
$(function()
{
    TaskDispatcher.run();
});

Note that I'm using my beloved jQuery to do the browser sniffing here, but naturally this could be written in a number of ways.

This pattern works best for small amounts of tasks. If you have a ton of tasks for IE6 but not others, then it may be better to use a conditional <script> tag or something that won't slow other browsers unnecessarily.