JavaScript

JavaScript: console logging (with IE safety)

Posted on by  
Richard Rijnberk

Every once in a while I work on a site which has some or copious amounts of javascript. Now I do not mind this at all. But it's pretty tedious stuff writing the code and putting in loggers. And when you're working on something and you have to test it on IE. Well let's just say the console may cause some problems. But rather then removing all the logging i've found there's an easy solution. Building yourself a logger like structure which checks the existence of the console before writing. That way you can add logging statements without crashing the entire application. A sample logger would look like this:

logger={
    log: function(message) {
        if(window.console && console.log) console.log(message)
    },
    dir: function(message) {
        if(window.console && console.dir) console.dir(message)
    }
}

// We can call this like so:
logger.log($("head title").text());

// or so:
logger.dir($("body"));

Continue reading →

shadow-left