Update the DOM vs Rerender the View In Angular

走远了吗. 提交于 2019-12-01 05:16:10

The DOM represents the HTML document loaded in the browser. JavaScript can manipulate the document through the DOM, but those manipulations do not take effect immediately but only after the JavaScript context that makes changes to the DOM is finished.

Think about it this way:

  • JS: Hey HTML document, I'm gonna make some changes to you.
  • HTML: Ok, go ahead, contact your friend the DOM and tell him what you want to change.
  • JS: OK, I'm on it...
  • JS: OK, I've made some changes, but hey, there's a few more things I need to change.
  • HTML: OK, go ahead, I'll wait until you finish everything.
  • JS: OK, done with everything
  • HTML: OK, I'll ask DOM what you've changed and apply those.

Consider the following test:

var a = document.body.children[0];

a.style.color = 'red'; 
for(var i = 0; i < 10000000000; i++) { }; 
a.style.color = 'blue';

Although there's considerable time between the instruction to change the color to red and the one to change it to blue, you will never see the color changing to red because all changes will be applied once the JS finished.

In fact, the color does change to red but only for such a short time period before it's changing to blue that the browser doesn't even have time to render the change. Or if it is, you won't notice.

In other words, DOM manipulations are queued by the browser. The queue will be executed once the JS context is finished. If JavaScript spends time between 2 DOM changes on other tasks, that will delay the start of the queue execution and then all queued changes will be executed in great succession.

In light of the above information, it should become clear that changing the DOM is not the same thing as changing the HTML document.

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