Script Injection for Late-Arriving Content
What you'll learn: How React automatically injects inline scripts to insert streamed HTML into the correct Suspense boundary placeholder after the initial page paint.
When you stream HTML out-of-order (as we learned in the previous lesson), React faces a challenge: how does late-arriving content know where to insert itself into the already-rendered page? The answer is automatic script injection.
How It Works
When React streams HTML for a Suspense boundary that hasn't resolved yet, it first sends a placeholder (like a loading spinner). When the suspended content finally resolves and arrives later in the stream, React doesn't just send the HTML—it wraps it in an inline <script> tag that contains JavaScript to place that HTML in the right spot.
Think of it like a package delivery service: the package (HTML content) arrives with instructions attached (the script) that tell it exactly which mailbox (Suspense boundary) it belongs to.
What the Script Does
The injected script:
- Contains the resolved HTML as a string
- Knows the unique ID of the target Suspense boundary
- Executes immediately when parsed by the browser
- Finds the placeholder element by ID
- Replaces it with the new HTML content
This happens before hydration—it's pure DOM manipulation that ensures the user sees complete content as soon as it arrives, even if React hasn't hydrated that part of the tree yet.
Why This Matters
This mechanism is what makes selective hydration and out-of-order streaming possible. Content can arrive in any order, and React ensures it lands in the correct location without waiting for everything to load or hydrate first.
Key Takeaway: React automatically injects inline scripts alongside late-arriving streamed HTML to insert content into the correct Suspense boundary placeholder, enabling out-of-order streaming and progressive page completion.