Performance: ScrollSpy component
ScrollSpy affects page interaction responsiveness and layout stability during scrolling.
const spy = new bootstrap.ScrollSpy(document.body, { target: '#navbar-example' });window.addEventListener('scroll', function() { document.querySelectorAll('section').forEach(section => { const rect = section.getBoundingClientRect(); if(rect.top <= 0 && rect.bottom >= 0) { document.querySelectorAll('.nav-link').forEach(link => link.classList.remove('active')); document.querySelector(`.nav-link[href='#${section.id}']`).classList.add('active'); } }); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual scroll event with getBoundingClientRect on every scroll | Many reads and writes | Multiple per scroll event | High due to style recalculations | [X] Bad |
| Bootstrap ScrollSpy native implementation | Minimal reads, optimized event handling | Single or none per scroll event | Low paint cost | [OK] Good |
data-bs-spy="scroll" tells Bootstrap to watch scroll events.data-bs-target points to the nav but does not activate ScrollSpy itself.<body data-bs-spy="scroll" data-bs-target="#navbar">
<nav id="navbar">
<a href="#section1">Section 1</a>
<a href="#section2">Section 2</a>
</nav>
<div id="section1">Content 1</div>
<div id="section2">Content 2</div>
</body>data-bs-spy="scroll" and data-bs-target="#navbar" attributes.<div id="scrollArea" data-bs-spy="scroll" data-bs-target="#menu">
<nav id="menu">
<a href="#part1">Part 1</a>
<a href="#part2">Part 2</a>
</nav>
<div id="part1">Content 1</div>
<div id="part2">Content 2</div>
</div>body is the scroll container, so add data-bs-spy="scroll" and data-bs-target there.position: relative; on the scroll containerposition: relative; for correct offset calculations.Pass the test and this pattern moves unknown