Add console.profile statements to JavaScript/jQuery code on the fly.

Posted by novogeek on Stack Overflow See other posts from Stack Overflow or by novogeek
Published on 2010-05-30T18:00:10Z Indexed on 2010/05/30 18:02 UTC
Read the original article Hit count: 195

Filed under:
|

Hi folks, We have a thick client app using jQuery heavily and want to profile the performance of the code using firebug's console.profile API. The problem is, I don't want to change the code to write the profile statements. Take this example:

var search=function(){
    this.init=function(){
        console.log('init');
    }
    this.ajax=function(){
        console.log('ajax');
        //make ajax call using $.ajax and do some DOM manipulations here..
    }
    this.cache=function(){
        console.log('cache');
    }
}
var instance=new search();
instance.ajax();

I want to profile my instance.ajax method, but I dont want to add profile statements in the code, as that makes it difficult to maintain the code.

I'm trying to override the methods using closures, like this: http://www.novogeek.com/post/2010/02/27/Overriding-jQueryJavaScript-functions-using-closures.aspx but am not very sure how I can achieve. Any pointers on this? I think this would help many big projects to profile the code easily without a big change in code.

Here is the idea. Just run the below code in firebug console, to know what I'm trying to achieve.

var search=function(){
    this.init=function(){
        console.log('init');
    }
    this.ajax=function(){
        console.log('ajax');
        //make ajax call using $.ajax and do some DOM manipulations here..
    }
    this.cache=function(){
        console.log('cache');
    }
}
var instance=new search();

$.each(instance, function(functionName, functionBody){
    (function(){
        var dup=functionBody
        functionBody=function(){
            console.log('modifying the old function: ',functionName);
            console.profile(functionName);
            dup.apply(this,arguments);
            console.profileEnd(functionName);
        }
    })();
    console.log(functionName, '::', functionBody());
});

Now what I need is, if i say instance.ajax(), I want the new ajax() method to be called, along with the console.profile statements. Hope I'm clear with the requirement. Please improvise the above code.

Regards, Krishna, http://www.novogeek.com

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery