Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the digest cycles have stabilized (aka "Has angular finished compilation?")

tl;dr: The initial question was "How to trigger a callback every digest cycle?" but the underlying question is much more interesting and since this answers both, I went ahead and modified the title. =)

Context: I'm trying to control when angular has finished compiling the HTML (for SEO prerendering reasons), after resolving all of its dependencies, ngincludes, API calls, etc. The "smartest" way I have found so far is via checking whether digest cycles have stabilized.
So I figured that if I run a callback each time a digest cycle is triggered and hold on to the current time, if no other cycle is triggered within an arbitrary lapse (2000ms), we can consider that the compilation has stabilized and the page is ready to be archived for SEO crawlers.

Progress so far: I figured watching $rootScope.$$phase would do but, while lots of interactions should trigger that watcher, I'm finding it only triggers once, at the very first load.

Here's my code:

app.run(function ($rootScope) {
  var lastTimeout;
  var off = $rootScope.$watch('$$phase', function (newPhase) {
    if (newPhase) {
      if (lastTimeout) {
        clearTimeout(lastTimeout);
      }
      lastTimeout = setTimeout(function () {
        alert('Page stabilized!');
      }, 2000);
    }
  });



Solution: Added Mr_Mig's solution (kudos) plus some improvements.

app.run(function ($rootScope) {
  var lastTimeout;
  var off = $rootScope.$watch(function () {
    if (lastTimeout) {
      clearTimeout(lastTimeout);
    }
    lastTimeout = setTimeout(function() {
      off(); // comment if you want to track every digest stabilization
      // custom logic
    }, 2000);
  });
});
like image 590
Phil Thomas Avatar asked Oct 20 '22 13:10

Phil Thomas


1 Answers

I actually do not know if my advice will answer your question, but you could simply pass a listener to the $watch function which will be called on each iteration:

$rootScope.$watch(function(oldVal, newVal){
    // add some logic here which will be called on each digest cycle
});

Have a look here: http://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch

like image 50
Mr_Mig Avatar answered Oct 23 '22 02:10

Mr_Mig