Skip to content

Instantly share code, notes, and snippets.

@eberlitz
Created June 27, 2016 17:34
Show Gist options
  • Save eberlitz/87e7af1ca2165f9af5c3359dec582bf0 to your computer and use it in GitHub Desktop.
Save eberlitz/87e7af1ca2165f9af5c3359dec582bf0 to your computer and use it in GitHub Desktop.
Ordered list of angular watchers in a page.
function humanReadableWatchExpression (fn) {
if (fn == null) {
return null;
}
if (fn.exp) {
fn = fn.exp;
} else if (fn.name) {
fn = fn.name;
}
return fn.toString();
}
function getWatchers(){
var root = angular.element(document.getElementsByTagName('body'));
var watchers = [];
var f = function (element) {
angular.forEach(['$scope', '$isolateScope'], function (scopeProperty) {
if (element.data() && element.data().hasOwnProperty(scopeProperty)) {
angular.forEach(element.data()[scopeProperty].$$watchers, function (watcher) {
watchers.push(watcher);
});
}
});
angular.forEach(element.children(), function (childElement) {
f(angular.element(childElement));
});
};
f(root);
// Remove duplicate watchers
var watchersWithoutDuplicates = [];
angular.forEach(watchers, function(item) {
if(watchersWithoutDuplicates.indexOf(item) < 0) {
watchersWithoutDuplicates.push(item);
}
});
return watchersWithoutDuplicates;
}
var watchers = getWatchers();
var expressions = watchers.map(humanReadableWatchExpression)
.reduce((col,exp)=>{
col[exp] = (col[exp]||0) + 1;
return col;
},{});
Object.keys(expressions).sort((a,b) => {
a = expressions[a];
b = expressions[b];
if (a === b) return 0;
if (a < b) return -1;
else return 1;
})
.forEach((a)=>{
console.info(expressions[a] + ':' + a);
});
console.info('Total watchers:',watchers.length);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment