Repository navigation
[4.x] Suspend component trees until their script modules load - #10631
Merged
Merged
Conversation
This was referenced Aug 29, 2026
A component's script module is fetched with an async import(), but Alpine walks the DOM synchronously — Alpine.data() providers and $js actions registered by the module didn't exist yet when the component's markup evaluated, producing "audioUploader is not defined" errors on initial load, dynamic mounts, lazy hydration, islands, and wire:navigate. Now the effect hook hands the module's promise to Alpine.deferInit(), so exactly the affected component's tree waits — visible, but uninitialized — while the rest of the page carries on. The module runs once the markup is in the DOM (updates gate on the response's morph landing), a failed load logs and initializes the tree anyway, and a component removed mid-flight never runs its script. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VxEoar4u3NVYop2jweewwf
Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VxEoar4u3NVYop2jweewwf
calebporzio
force-pushed
the
claude/defer-init-for-script-modules
branch
from
August 30, 2026 12:01
e2eddf0 to
e992667
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The problem
A component's co-located
<script>compiles to an ES module fetched with a dynamicimport(). Alpine walks the DOM synchronously. That race is unwinnable as stated: even a byte-for-byte cached module settles no earlier than the next microtask, which is after the walk has already evaluated the component's markup. So:throws
Alpine Expression Error: audioUploader is not defined— on initial load, dynamic mounts, lazy hydration, islands, andwire:navigate. The "first instance always breaks, later instances work" signature in the reports comes from the first instance's laterun()registering the name globally for everyone after it.This is the successor to #10295/#10619/#10623 (and #9861 before them), reimplemented from scratch. Fixes #9591, #9737, #9830.
The fix
One invariant, enforced at one choke point: a component's subtree never Alpine-initializes before its script module has settled (executed or failed).
The effect hook starts the
import()immediately, then hands a readiness promise toAlpine.deferInit(component.el, ready)— the new upstream primitive (alpinejs/alpine#4887) that suspends exactly that tree, visible but uninitialized, while the rest of the page carries on. Alpine owns the suspension mechanics (clone mirroring, mutation replay, removal, nesting); Livewire only declares the prerequisite.Because the same choke point sits under every entry path, all of them are fixed by the same few lines: initial load and back/forward (fresh roots in the start walk), dynamic children (fresh roots mid-morph), lazy hydration (live root suspended before the awaited morph applies), islands and slots (fresh roots in fragment morphs), and
wire:navigate(fresh roots after the swap).The script-timing contract
The fix forces a uniform, documentable contract that previously existed only as an accident of racing — a component's script runs when its markup is in the DOM, but before Alpine initializes it:
Alpine.data(),$jsactions, directives) are guaranteed to exist before any expression in the component's markup evaluates.$wire.$eland DOM queries work — for updates,run()is gated on the response's morph landing (morphGateFor), so a lazy component's script sees its real markup, not the placeholder.$refs, Alpine state) doesn't exist yet — use aninit()hook or$wire.$nextTick(). This is the one behavioral edge relative to scripts that "worked" before, and it's documented indocs/javascript.md.x-cloakis honored through the loading window.Failure and interruption semantics
console.errornaming the component, then the tree initializes without it. The page stays alive; sibling components are untouched.finallyguarantees the suspension always releases.onMorphed, and as a backstop ononCancel/onFailure/onError/onFinish— however a message ends, no component stays suspended.run()), and Alpine skips initializing the disconnected tree.lifecycle.jsafterinitComponentmakeswire:directive triggers fire once, on the resume pass, instead of doubling up across both passes.Compatibility
scriptModuleeffect — behavior is byte-identical.Alpine.deferInitis feature-detected: with an older bundled Alpine the loader degrades to today's (racy) behavior instead of breaking. This PR needs the Alpine release containingdeferInitplus anpm run bump-alpineto go green in CI — see dependency note below.$jspromise-proxy in$wire.jsstays as a safety net for late$jsaccess from outside the component.@alpinejs/cspshares Alpine's core API surface).Tests
src/Features/SupportJsModules/BrowserTest.php— 16 tests: the 4 existing module tests, plus initial load (x-dataon the component's own root — the hardest case), two instances on one page (the first-instance race), post-morph survival, dynamic child, lazy hydration, island-mounted child,wire:navigate(including a second navigation reusing the cached module),x-cloakthrough a deterministically-held loading window (client-gated module via top-levelawait, so the single-threaded test server never serializes the timeline), removal mid-flight, failed import and throwing script fail-open (each asserting the broken component's own tree still initializes), and a lazy DOM-probe that pins the morph-gate contract: a lazy component whose module is already cached records whether its script saw real markup or the placeholder.Regression batches run green: SupportLazyLoading (23), SupportIslands (33), SupportNavigate (59), SupportScriptsAndAssets (16), SupportSlots, SupportEvents (22), plus the JS unit suite (110) — all against a locally built Alpine including
deferInit, and the full Alpine Cypress suite passes with the primitive in place.Dependency
Merge order: alpinejs/alpine deferInit PR → Alpine release →
npm run bump-alpinehere → this PR goes green. Until the bump, the feature-detect keeps the bundle safe but the new browser tests fail (they assert the fixed behavior).A follow-up PR (
claude/eager-script-module-delivery) layers eager module delivery on top —modulepreloadhead links and achildScriptModulesprefetch — shrinking the suspended window to near zero. It's split out because it's pure latency work; this PR is the correctness story.Hardening from adversarial review
Three defects found in review are fixed here beyond the original design:
initComponentnow checkstreeIsSuspendedFor()(deferInit present AND module pending) instead of just "module pending" — otherwise, on an Alpine withoutdeferInit, the root'swire:directive triggers would be skipped on the only pass that ever runs.scriptModuleeffect (tracked viaonSync), so a concurrent message for the same component finishing first can't open it early and run the script against placeholder markup._x_marker) — their directives are picked up exactly once by the tree walk when the suspended tree resumes.Known, accepted edge:
$jspromise-proxy calls made before a module that then fails to load remain unsettled (same as today's failure mode); the failure itself is loudly logged.🤖 Generated with Claude Code
https://claude.ai/code/session_01VxEoar4u3NVYop2jweewwf