Alerts3 Cart0 GitHub

Streaming pagelets

This page was sent before its parts were ready. Every pagelet waits for a slow “API”, is rendered at the same time as the others, and is flushed into its placeholder as soon as it is done. One of them fails and shows its fallback; one waits for a later phase.
  • defer() and content()

    The content is rendered when the pagelet is, not when the page is built.

  • BigPipe::stream()

    Flushes the page, then every pagelet as soon as it is rendered.

  • BigPipe::setParallel(true)

    Pagelets that wait with Pagelet::sleep() or await() do not hold up each other.

  • setFallback()

    A pagelet that throws is replaced by its fallback, the page goes on.

  • setPhase()

    A pagelet of a later phase is shown after the earlier ones.

  • refreshPagelet()

    A response renders a pagelet again and replaces it.

  • BigPipe::setHtmlContainers(true)

    The HTML of a pagelet goes into a hidden <code> container before its script, instead of the JSON. See HTML containers.

Controller.php
class FeedPagelet extends Pagelet
{
    protected mixed $fallback = '<p>The feed is not available.</p>';

    protected function content(): string
    {
        // Waits without blocking the other pagelets.
        $posts = Pagelet::await(fn () => $this->api->poll());

        return view('feed', ['posts' => $posts])->render();
    }
}

// The controller
BigPipe::setParallel(true);
BigPipe::setHtmlContainers(true); // the HTML outside of the JSON

return response()->stream(function () {
    echo view('page', ['feed' => new FeedPagelet()])->render();
    BigPipe::stream();             // every pagelet when it is ready
    echo '</body></html>';
}, 200, ['X-Accel-Buffering' => 'no']);
Try it
layout flushed at
19 ms
last pagelet rendered at
…
phase 0 shown at
…
phase 1 shown at
…
Profile #pagelet_profile
API
200 ms
rendered at
220 ms
shown at
…
Feed #pagelet_feed
API
1200 ms
rendered at
1421 ms
shown at
…
Statistics #pagelet_stats
API
700 ms
rendered at
2122 ms
shown at
…
Ads #pagelet_ads

The API failed: this is the fallback of the pagelet. The rest of the page is fine.

API
500 ms
rendered at
2623 ms
shown at
…
Suggestions phase 1
API
300 ms
rendered at
2924 ms
shown at
…

Five pagelets, one response

The layout was flushed first, then every pagelet as soon as it was rendered; the bars end where each one was. Suggestions is in phase 1: rendered early, it is sent after the others. Shown at is when the browser displayed it (with the Vite dev server, once the page is parsed); a phase is shown once its last pagelet is, without waiting for the next phase. Switch to one after another and compare. HTML containers: view the source of the page, every pagelet has its HTML in a hidden &lt;code&gt; before its script, which only names the container; a page transition is JSON, so these links load the page in full.