#htmx
#html
#frontend
Day 11: Infinite Scroll & Lazy Load
Welcome to Day 11.
Infinite scroll is notoriously hard to get right in JS. In htmx, itâs trivial using revealed.
The Mechanism
- Render a list of 10 items.
- The last item has a special trigger:
hx-trigger="revealed". - When the user scrolls to it, it requests page 2.
- Page 2 replaces the last item with⌠Page 2 content (items 11-20).
The Code
<!-- Items 1-9 -->
<div class="item">Item 1</div>
...
<div class="item">Item 9</div>
<!-- Item 10: The Wire -->
<div class="item"
hx-get="/page/2"
hx-trigger="revealed"
hx-swap="afterend">
Item 10
</div>
Wait, afterend?
If we use afterend, Item 10 stays, and new items appear after it.
The âItem 20â in the response will need the same trigger code pointing to Page 3.
Lazy Loading (Skeleton UI)
Donât block the page load for expensive data (like a dashboard chart).
<!-- Initial HTML -->
<div>
<h1>Dashboard</h1>
<div hx-get="/graph" hx-trigger="load">
<div class="skeleton-loader">Loading Graph...</div>
</div>
</div>
The user sees the page instantly. The graph pops in 200ms later.
Challenge for Day 11
- Build a âClick to Load Moreâ button first.
- Change it to âInfinite Scrollâ by changing
hx-trigger="click"tohx-trigger="revealed".
Solution:
<tr hx-get="/contacts/?page=2" hx-trigger="revealed" hx-swap="afterend">
<td>Last Contact on Page 1</td>
</tr>
Tomorrow: Click To Edit.