Performance of MutationObserver and ways to improve it

时光毁灭记忆、已成空白 提交于 2021-01-29 17:22:39

问题


I have some questions regarding MutationObserver and ways to improve it. From that answer:

  1. Use debounce or a similar technique e.g. accumulate mutations in an outer array and schedule a run via setTimeout / requestIdleCallback / requestAnimationFrame:

    const queue = [];
    const mo = new MutationObserver(mutations => {
      if (!queue.length) requestAnimationFrame(process);
        queue.push(mutations);
    });
    function process() {
      for (const mutations of queue) {
        // ..........
      }
      queue.length = 0;
    }
    
  1. Is it possible to use the above code only for addedNodes? I don't care for removedNodes. If possible, then how? Does it worth it? Or it's pretty useless and/or not faster/more performant?
  2. "for ... of" isn't slower than "for (var i=0 ; ..."?
  3. The above code seems to not work all the times when used in an inactive tab. I use a setTimeout on the next line after "for (const mutations of queue) {". Most likely it is caused by setTimeout. Any ways to fix this? I need setTimeout to randomize time to call a function and I would like to make it work even when tab is inactive.

来源:https://stackoverflow.com/questions/65554806/performance-of-mutationobserver-and-ways-to-improve-it

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