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

怎甘沉沦 提交于 2019-12-04 13:04:09

问题


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);
  });
});

回答1:


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



来源:https://stackoverflow.com/questions/22039251/how-to-check-if-the-digest-cycles-have-stabilized-aka-has-angular-finished-com

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!