问题
I have some questions regarding MutationObserver and ways to improve it. From that answer:
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; }
- 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?
- "for ... of" isn't slower than "for (var i=0 ; ..."?
- 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