Checking javascript usage site-wide


(Oleg Voronin) #1

I'm looking at re-factoring some legacy JS used by our Squiz Matrix site. The bulk of this effort will involve looking at functions like `myGodWhyIsThisEvenHere()` and trying to locate the page where it's being used.

 

Unlike a conventional dev environment, I can't simply search for such usage with AgentRansack etc. while the Quick Search in the _admin view naturally can't look for such content.

 

How do you normally tackle these tasks? Perhaps I could export the current site's "snapshot" as... xml? and search through it locally?


(Anthony Barnes) #2

Searching for where JS is used, not just where it written, is incredibly difficult because there could be any number of things that occur on the page that the JS might be conditionally checking before it runs a function, totally depends how it's written. You could insert some tracking code by overloading the function that would let you run some custom javascript.

 

For example:

// Overload an existing function in the global scope
var _oldFn = myGodWhyIsThisEvenHere;
myGodWhyIsThisEvenHere = function() {
    var args = Array.prototype.slice.call(arguments);
    //... Your tracking code
    _oldFn.apply(window, args);
}

Or even better, wrap the function with something like this: http://underscorejs.org/#wrap

 

For the tracking part of it you could write a custom script, or send http requests to a page where you can use the web server logs to record things like HTTP REFERRER headers, or use something like google analytics event tracking: https://developers.google.com/analytics/devguides/collection/analyticsjs/events

 

If the function is used in a loop, or likely to be called many times on a page you'd want to setup something like this function http://underscorejs.org/#once to prevent multiple calls to the tracking code.

 

Is this the kind of stuff you were after? I'm not sure if you meant the function may have been written in the contents of a page, if so maybe a simple SQL query run in the database could find it's context.