Created
June 27, 2016 17:34
-
-
Save eberlitz/87e7af1ca2165f9af5c3359dec582bf0 to your computer and use it in GitHub Desktop.
Ordered list of angular watchers in a page.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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