#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

  1. Render a list of 10 items.
  2. The last item has a special trigger: hx-trigger="revealed".
  3. When the user scrolls to it, it requests page 2.
  4. 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

  1. Build a “Click to Load More” button first.
  2. Change it to “Infinite Scroll” by changing hx-trigger="click" to hx-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.