Repository navigation
Add Alpine.deferInit() — suspend a tree until an async prerequisite settles - #4887
Merged
Merged
Conversation
Integrations that load JavaScript for a component asynchronously — a script module registering an Alpine.data() provider, for example — lose a race against Alpine's synchronous walk: x-data evaluates before the registration exists. Until now the only way out was juggling private state (_x_ignore, _x_marker, clone interceptors) from the outside. Alpine.deferInit(el, promise) suspends initialization of one element's tree until the promise settles, while the rest of the page initializes normally. Suspension rides on the ignore flag, so the walker, directive handlers, and added-node initialization all already respect the boundary; the new pieces are the bookkeeping around it: - Attribute mutations inside a suspended tree are held and replayed on resume instead of evaluating against a half-ready tree. - Morph clones mirror the suspension so detached directive evaluation can't slip past it. - Rejections surface through Alpine's error handler and the tree initializes anyway — a failed prerequisite never wedges a tree. - An element removed while suspended never initializes; if it re-enters the DOM it's picked up like any added node. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VxEoar4u3NVYop2jweewwf
Collaborator
Author
|
The Livewire consumer PR is up: livewire/livewire#10631 (with a latency follow-up in livewire/livewire#10632). Merge order: this → Alpine release → |
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
Alpine initializes a tree of elements synchronously. Integrations that load JavaScript for a component asynchronously — Livewire's co-located script modules registering
Alpine.data()providers, for example — lose that race: Alpine evaluatesx-data="audioUploader"before the registration exists, and the tree initializes broken.Until now the only way out was juggling private state from the outside — setting
_x_ignore, clearing_x_marker, mirroring flags throughinterceptClone, and manually re-runninginitTree(). Every consumer of that approach has to rediscover the same sharp edges (detached morph clones, mutations during the window, double-initialized directives).The API
One method:
Alpine.deferInit(el, promise). While suspended, nothing inside the tree initializes — directives don't evaluate, nodes added inside it wait, attribute changes are held — and the rest of the page initializes normally. When every registered promise settles, the tree initializes in place.The contract
interceptInitcallback before the element initializes, or on a live element to suspend future activity in its tree (e.g. ahead of a morph that brings in new markup).deferInit()again before resume adds a prerequisite; the tree initializes after all of them settle.widgetIsLoaded()check above), so the resume pass initializes normally.x-cloakis honored through the suspended window — the attribute is only removed when the element actually initializes.alpine:initializeddoes not wait for suspended trees.The implementation
The design insight that keeps this small: suspension rides on the existing ignore flag.
initTree's walker,getDirectiveHandler's_x_ignorecheck, and the added-node path's closest-ignored check already implement "don't initialize this tree" —deferInitsets the flag (tracking whether it owned it) and records the suspension on the element. The new code is only the bookkeeping the flag can't do alone:lifecycle.jsroutes the attributes-added handler through the queue). Without this, a morph that addsx-datato a live root during the window would either evaluate too early or be dropped forever. Replay only touches elements that already carry an_x_marker— everything else is covered by the resume walk.interceptClone): morphing evaluates directives on detached clones where the live tree's flag can't be seen.flushPendingMutations()inmutation.js), so everything the observer saw during the window lands in the queue while the tree is still suspended, instead of firing against a half-ready tree.initTree(el): an already-marked root skips itself but walks its children; a fresh root re-enters interception and initializes normally. No continuation capture, no marker surgery.Pages that never call
deferInit()hit one added check: a counter guard (activeDefers === 0) in the attributes-added handler, and the same guard first in the clone interceptor. Zero defers → zero extra work.Tests
tests/cypress/integration/defer-init.spec.js— 12 specs: suspension until resolve, tree isolation, multiple promises, rejection fail-open,x-cloakhonoring, nodes added during suspension, attribute replay on live elements, nested suspension composing, removal during suspension, the interceptor-rerun contract, morph-while-suspended (exercising the clone mirroring), and a removed element re-entering the DOM after settlement. Full existing Cypress suite (all 62 spec files) and Vitest pass unchanged.The implementation was additionally hardened against three edges found in adversarial review:
settle()is re-entrancy-safe when a handler running during its mutation flush registers a new prerequisite on the same element; queued-attribute entries are pinned to the element's marker so an element that left the tree and re-initialized elsewhere is never double-initialized; and a replay that finds an enclosing tree still suspended hands its entries to that tree instead of evaluating under it.One known edge is documented rather than handled: swapping the
x-dataattribute on an already-initialized element mid-suspension splits its cleanup (immediate) from its re-initialization (at resume) — the same children-hold-stale-scope behavior the un-suspended path has, stretched over the suspension window.Motivation
Built as the foundation for fixing livewire/livewire's "component script module vs. Alpine init" race (discussions livewire/livewire#9591, #9737, #9830; prior attempts livewire/livewire#9861, #10295, #10619, #10623). The Livewire consumer PR follows. The
@alpinejs/cspbuild picks the method up automatically since it sharessrc/alpine.js.🤖 Generated with Claude Code
https://claude.ai/code/session_01VxEoar4u3NVYop2jweewwf