Skip to content

Instantly share code, notes, and snippets.

@lephuongbg
Last active January 20, 2016 08:30
Show Gist options
  • Save lephuongbg/cf39ac9d3ad6e78b321c to your computer and use it in GitHub Desktop.
Save lephuongbg/cf39ac9d3ad6e78b321c to your computer and use it in GitHub Desktop.
Chrome snippet to analyze AngularJS scopes
var scopeStats = function() {
console.log('Start analyzing...');
var scopes = [], $rootScope = $('html').scope(), traverse;
scopes.elements = {};
traverse = function(scope, callback) {
callback(scope);
var child_scope = scope.$$childHead;
while (child_scope) {
traverse(child_scope, callback);
child_scope = child_scope.$$nextSibling;
}
};
traverse($rootScope, function(scope) {
if (scope.$$watchersCount == 0) {
return;
}
if (scopes.indexOf(scope) === -1) {
scopes.push(scope);
}
});
$('.ng-scope').each(function(_, element) {
var scope = $(element).scope();
if (!scopes.elements[scope.$id]) {
scopes.elements[scope.$id] = element;
}
});
scopes.forEach(function(scope, index) {
if (index > 0) {
if (scopes[index - 1].$parent == scope.$parent) {
console.groupEnd();
} else if (scope.$parent != scopes[index - 1]) {
parent = scopes[index - 1].$parent;
console.groupEnd();
while (parent && parent != scope.$parent) {
console.groupEnd();
parent = parent.$parent;
}
}
}
if (scope.$id > 1) {
console.groupCollapsed("Scope %d (%d - %f%%)",
scope.$id,
scope.$$watchersCount,
parseFloat((scope.$$watchersCount / scope.$parent.$$watchersCount * 100).toFixed(2))
);
} else {
console.groupCollapsed("Scope %d (%d)", scope.$id, scope.$$watchersCount);
}
console.log("Scope:", scope);
console.log("Watchers:", scope.$$watchers.length);
var child_count = 0, child_stat = {}, child_scope = scope.$$childHead, child_stat_string = "";
while(child_scope) {
child_count++;
if (!child_stat[child_scope.$$watchersCount + ' watcher(s)']) {
child_stat[child_scope.$$watchersCount + ' watcher(s)'] = 1;
} else {
child_stat[child_scope.$$watchersCount + ' watcher(s)']++;
}
child_scope = child_scope.$$nextSibling;
}
if (child_count > 0) {
console.log("Children: %d (stats: %o)", child_count, child_stat);
}
if (scopes.elements[scope.$id]) {
console.log("Element:", scopes.elements[scope.$id]);
}
});
// End last group
console.groupEnd();
// End all last group's ancestors' group
parent = scopes[scopes.length - 1].$parent;
while (parent) {
console.groupEnd();
parent = parent.$parent;
}
return 'Done analyzing!';
}
scopeStats();

Chrome snippet to analyze AngularJS scopes (counting watchers, listing children, etc)

How to use

  1. Open Chrome Developer Tools > Sources > Snippets, create a new snippet.
  2. Copy and paste content of scope-stats.js into it then save.
  3. Right click on snippet and choose Run
  4. Subsequent runs only need to execute scopeStats() inside console
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment