I run Boat Build Log, a free site where amateur boat builders keep a log of their build. A log is a list of dated entries, each with a paragraph or two and up to a couple dozen photos. Some builds take two years, so some logs get long.
A reader wrote in about a fourteen-entry log. He didn't like having to find and press "Later entries" at the foot of every page. He wanted the next page to just show up as he scrolled. Fair request, and it sounds like an afternoon of work. It mostly was. Then I shipped two bugs with it, and I'll walk through both.
Why the log is paged in the first place
The log page used to load every entry with all its media and comments in one response. That was fine at eleven entries. It wasn't fine for a Glen-L Squirt log, which was a two-year build with every photo coming down the wire as a single page. So the controller pages it, five entries at a time:
public const ENTRIES_PER_PAGE = 5; Five is a reading unit, not a performance number. It's about a screenful of scrolling on a phone. The query is split in two: all the entry ids in order first, then the full rows for one page.
$pageIds = $ordered->slice(($page - 1) * self::ENTRIES_PER_PAGE, self::ENTRIES_PER_PAGE)->values(); $rows = Entry::whereIn('id', $pageIds) ->withCount('likes') ->with(['media', 'phase', 'author', /* comments trimmed */]) ->get() ->sortBy(fn ($e) => $pageIds->search($e->id)) ->values(); The page number lives in the path, so page two of a log is /page/2 on the end of the log's address, not ?page=2. A small PathPaginator class extends Laravel's LengthAwarePaginator and overrides url() to do that:
$base = rtrim($this->path(), '/'); $url = $page === 1 ? $base : $base.'/page/'.$page; Page one keeps the bare address. /page/1 and the old ?page= form both get a 301 to the real one, and a page number past the end redirects to the last page. One page, one URL. Each page is its own canonical, with rel="prev" and rel="next" in the head.
The rule: the pager stays, the script sits on top
Here's the part I wasn't willing to give up. Those paged URLs are what search engines index, and a crawler doesn't scroll. If the later entries of a log only exist after a scroll event fires, the log has lost the entries that bring people in from search. So continuous scrolling had to be progressive enhancement and nothing more.
The Blade view marks the pager with one attribute and only sends the script when the log has more than one page:
@if($entries->hasPages()) @push('scripts') <script src="{{ \App\Support\Asset::url('js/log-scroll.js') }}" defer></script> @endpush <nav class="build-pager no-print" aria-label="More of this log" data-scroll> ... @if($entries->nextPageUrl()) <a class="btn btn-sm push" rel="next" href="{{ $entries->nextPageUrl() }}">Later entries →</a> @endif With JavaScript off, or on an old browser, you get exactly the pager you had before. The script bails out early if it can't do the job:
var pager = document.querySelector('nav.build-pager[data-scroll]'); if (!pager) return; if (!('IntersectionObserver' in window) || !window.fetch || !window.DOMParser) return; Fetching the page the server already renders
I didn't build a JSON endpoint for this. The next page is fetched as the same HTML a browser would get, and the script lifts the entry sections out of it. One rendering path, nothing to keep in step.
An IntersectionObserver watches the pager with a 600px margin, so the fetch starts before the reader actually reaches the foot:
var observer = new IntersectionObserver(function (seen) { for (var i = 0; i < seen.length; i++) { if (seen[i].isIntersecting) { load(); break; } } }, { rootMargin: '600px 0px' }); observer.observe(pager); load() reads the href off the real "Later entries" link, fetches it, and parses the response:
var doc = new DOMParser().parseFromString(html, 'text/html'); var entries = doc.querySelectorAll('.log section.entry'); if (!entries.length) throw new Error('no entries in response'); The sections are adopted into the live document and inserted after the last entry on screen, so the pager stays at the foot. Then the script copies two things from the fetched page into the live pager: the "Page 2 of 3" count, and the next link's href. If the fetched page has no next link, the link is removed and the observer disconnects. The pager always describes the last page loaded.
Likes, the lightbox and comment forms work inside the new entries without any re-initializing, because those behaviors were already delegated from the document.
Moving the address bar
After a page lands, the address moves on to it:
try { history.replaceState(history.state, '', url); } catch (e) { /* file: or sandbox */ } It's replaceState, not pushState, so Back leaves the log instead of stepping backwards through every page you scrolled past. A copied link or a reload lands on the page you were reading.
Just to be straight about the limits: this only loads downward. If you reload on /page/3, the server renders page three's five entries and an "Earlier entries" link, and that link is a plain link. Nothing loads above you in place. I haven't needed it yet, and a plain link is good enough until someone asks.
If a fetch fails, the script sets a failed flag, disconnects the observer, and leaves the link alone. It still works as a link. A click on "Later entries" while the script is healthy loads in place, but modified clicks are skipped so Ctrl+click still opens a tab.
Bug one: -1 === -1
Each log has a "jump to" rail down the side with one link per month. The rail spans the whole log, so each link carries the page its entry is on plus a fragment, something like /page/4#entry-123. Once page four is on screen, that link should scroll, not reload. So after each load the script cuts matching links down to the bare fragment.
My first version decided "is this link on the page I just loaded" with a hand-rolled ends-with test:
if (target === base || (target && base.indexOf(target) === base.length - target.length)) { Look at what happens when base ends in /page/2 and target ends in /page/10. The target isn't found, so indexOf returns -1. The target is one character longer than the base, so the length difference is also -1. They match.
So loading page two trimmed every month link for /page/10 and /page/11 down to a fragment of an entry that wasn't on screen. Pressing those months did nothing at all. It only bites on logs with ten or more pages, which is fifty-plus entries, which is exactly the logs the rail exists for. My test logs were all shorter than that.
The fix compares whole paths:
function pathOf(href) { try { var u = new URL(href, location.href); return u.origin === location.origin ? u.pathname.replace(/\/+$/, '') : null; } catch (e) { return null; } } and then simply if (pathOf(href.slice(0, hash)) === base). Lesson relearned: don't write string suffix checks by hand when the thing you're comparing is a URL.
Bug two: the page that loaded where nobody was looking
The second one wasn't a logic error. Below the pager there's more page: related builds, costs and so on. A reader who flings the page to the bottom on a phone ends up down there, past the pager, when the next page arrives. The new entries go in above them. Nothing on screen changes, and it looks like nothing happened.
So now the script checks where the reader is after an insert:
if (firstNew && pager.getBoundingClientRect().bottom < 0) { if (!noteTarget) noteFrom = before + 1; showNote(noteTarget || firstNew, noteFrom, log.querySelectorAll('section.entry').length); } If the pager is above the viewport, a small fixed note says "Entries 6 to 10 loaded above." with a "Show them" button that scrolls to the first new entry. A second observer hides the note once that entry comes on screen. If another page loads while the note is up, it keeps pointing at the first unseen entry and stretches the range. Somebody reading down normally never sees it.
What the tests can and can't pin
A PHPUnit feature test can't scroll. So LogScrollTest pins the contract between the markup and the script instead: a fourteen-entry log sends the script, the data-scroll hook and a rel="next" link ending in /page/2; the last page has no next link; a three-entry log sends neither; and page two really does carry five section.entry elements inside div.log for the script to lift.
$this->assertSame(5, preg_match_all('~<section class="entry" id="entry-\d+"~', $html)); Neither bug above would have been caught by those tests. Both were found by reading real long logs on a phone. If you add something like this, go fling a fifty-entry page around before you call it done.
You can see it working on any of the longer logs under wooden boat build logs. And if you've got a boat taking shape in the garage, Boat Build Log is free. Feel free to borrow the pattern for your own paged lists.

