JavaScript:路口观察器 VS 滚动

Maz*_* Li 7 javascript browser scroll rendering intersection-observer

我想测试大内容的渲染效果\n所以,我使用两种方式来测试滚动10000个文本div时的速度

\n\n
// getBoundingClientRect\nfunction lazyLoading_useRect() {\n    let root = document.getElementById(\'root\');\n\n    root.addEventListener(\'scroll\', function(e) {\n        root.childNodes[0].childNodes.forEach(node => {\n            let nodeTop = node.getBoundingClientRect().top; \n            if (nodeTop > -root.offsetHeight && nodeTop < root.offsetHeight) displayBlock(node, true);\n            else displayBlock(node, false);\n        });\n\n    });\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

\n\n
function lazyLoading_useIO() {\n    function callback(entries, observer) {\n        entries.forEach((entry, index)\xc2\xa0=>\xc2\xa0{\n            if (entry.isIntersecting) { \n                displayBlock(entry.target, true);\n            } else {\n                displayBlock(entry.target, false);\n            }\xc2\xa0\n      });\xc2\xa0\xc2\xa0\n    }\n\n    const\xc2\xa0options\xc2\xa0=\xc2\xa0{\n      root:\xc2\xa0document.querySelector(\'#root\'),\n      rootMargin:\xc2\xa0\'0px\',\n      threshold:\xc2\xa0[0]\n    };\xc2\xa0\xc2\xa0\n\n    const\xc2\xa0observer\xc2\xa0=\xc2\xa0new\xc2\xa0IntersectionObserver(callback,\xc2\xa0options);\n    const\xc2\xa0eles\xc2\xa0=\xc2\xa0document.querySelectorAll(\'#block\');\xc2\xa0\n    eles.forEach(ele => observer.observe(ele));\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我以为IntersectionObserver会比getBoundingClientRect更快\n但是为什么IntersectionObserver要花很多时间来绘制呢?

\n\n

在此输入图像描述

\n