Skip to content

[4.x] Suspend component trees until their script modules load - #10631

Merged
calebporzio merged 2 commits into
4.xfrom
claude/defer-init-for-script-modules
Aug 30, 2026
Merged

calebporzio merged 2 commits into
4.xfrom
claude/defer-init-for-script-modules

Conversation

@calebporzio

Copy link
Copy Markdown
Collaborator

The problem

A component's co-located <script> compiles to an ES module fetched with a dynamic import(). 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:

<div x-data="audioUploader">
    <span x-text="message"></span>
</div>

<script>
    Alpine.data('audioUploader', () => ({ message: 'Loaded' }))
</script>

throws Alpine Expression Error: audioUploader is not defined — on initial load, dynamic mounts, lazy hydration, islands, and wire:navigate. The "first instance always breaks, later instances work" signature in the reports comes from the first instance's late run() 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 to Alpine.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:

  • Registrations (Alpine.data(), $js actions, directives) are guaranteed to exist before any expression in the component's markup evaluates.
  • $wire.$el and 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.
  • Anything produced by initializing the markup ($refs, Alpine state) doesn't exist yet — use an init() hook or $wire.$nextTick(). This is the one behavioral edge relative to scripts that "worked" before, and it's documented in docs/javascript.md.
  • x-cloak is honored through the loading window.

Failure and interruption semantics

  • Fail open. A module that 404s or a script that throws logs a console.error naming the component, then the tree initializes without it. The page stays alive; sibling components are untouched. finally guarantees the suspension always releases.
  • The morph gate always opens. It resolves on onMorphed, and as a backstop on onCancel/onFailure/onError/onFinish — however a message ends, no component stays suspended.
  • Removal mid-flight. A component removed while its module loads never runs its script (connectivity check before run()), and Alpine skips initializing the disconnected tree.
  • The early return in lifecycle.js after initComponent makes wire: directive triggers fire once, on the resume pass, instead of doubling up across both passes.

Compatibility

  • Components without co-located JS: every new branch is guarded on the scriptModule effect — behavior is byte-identical.
  • Alpine.deferInit is feature-detected: with an older bundled Alpine the loader degrades to today's (racy) behavior instead of breaking. This PR needs the Alpine release containing deferInit plus a npm run bump-alpine to go green in CI — see dependency note below.
  • The $js promise-proxy in $wire.js stays as a safety net for late $js access from outside the component.
  • CSP builds pick the primitive up automatically once Alpine ships it (@alpinejs/csp shares Alpine's core API surface).

Tests

src/Features/SupportJsModules/BrowserTest.php — 16 tests: the 4 existing module tests, plus initial load (x-data on 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-cloak through a deterministically-held loading window (client-gated module via top-level await, 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-alpine here → 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 — modulepreload head links and a childScriptModules prefetch — 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:

  • Degraded-path regression: the early return after initComponent now checks treeIsSuspendedFor() (deferInit present AND module pending) instead of just "module pending" — otherwise, on an Alpine without deferInit, the root's wire: directive triggers would be skipped on the only pass that ever runs.
  • Message-keyed morph gate: the gate binds to the exact message that carried the scriptModule effect (tracked via onSync), so a concurrent message for the same component finishing first can't open it early and run the script against placeholder markup.
  • No double directive triggers: Livewire's own attributes-added handler now skips elements Alpine hasn't initialized (no _x_marker) — their directives are picked up exactly once by the tree walk when the suspended tree resumes.

Known, accepted edge: $js promise-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

calebporzio and others added 2 commits August 30, 2026 08:00
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
@calebporzio
calebporzio force-pushed the claude/defer-init-for-script-modules branch from e2eddf0 to e992667 Compare August 30, 2026 12:01
@calebporzio
calebporzio merged commit 33874a8 into 4.x Aug 30, 2026
32 checks passed
@calebporzio
calebporzio deleted the claude/defer-init-for-script-modules branch August 30, 2026 12:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant