Skip to content

Add Alpine.deferInit() — suspend a tree until an async prerequisite settles - #4887

Merged
calebporzio merged 1 commit into
mainfrom
claude/defer-tree-init
Aug 30, 2026
Merged

calebporzio merged 1 commit into
mainfrom
claude/defer-tree-init

Conversation

@calebporzio

Copy link
Copy Markdown
Collaborator

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 evaluates x-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 through interceptClone, and manually re-running initTree(). Every consumer of that approach has to rediscover the same sharp edges (detached morph clones, mutations during the window, double-initialized directives).

The API

Alpine.interceptInit(el => {
    if (el.hasAttribute('data-widget') && ! widgetIsLoaded(el)) {
        Alpine.deferInit(el, loadWidget(el))
    }
})

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

  • Registration is synchronous — from an interceptInit callback 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).
  • Multiple promises compose — calling deferInit() again before resume adds a prerequisite; the tree initializes after all of them settle.
  • Rejection fails open — the error goes through Alpine's error handler, then the tree initializes anyway. A failed prerequisite never wedges a tree.
  • Removal is safe — an element that left the DOM never initializes; if it re-enters, the mutation observer picks it up like any added node.
  • Interceptors run again on resume for elements that hadn't initialized yet. Consumers defer only while their prerequisite is outstanding (like the widgetIsLoaded() check above), so the resume pass initializes normally.
  • x-cloak is honored through the suspended window — the attribute is only removed when the element actually initializes.
  • alpine:initialized does 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_ignore check, and the added-node path's closest-ignored check already implement "don't initialize this tree" — deferInit sets 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:

  • Attribute mutations inside a suspended tree are queued and replayed on resume (lifecycle.js routes the attributes-added handler through the queue). Without this, a morph that adds x-data to 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.
  • Morph clones mirror the suspension (interceptClone): morphing evaluates directives on detached clones where the live tree's flag can't be seen.
  • Settlement flushes pending mutations synchronously first (flushPendingMutations() in mutation.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.
  • Resume is just 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-cloak honoring, 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-data attribute 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/csp build picks the method up automatically since it shares src/alpine.js.

🤖 Generated with Claude Code

https://claude.ai/code/session_01VxEoar4u3NVYop2jweewwf

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
@calebporzio

Copy link
Copy Markdown
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 → npm run bump-alpine in livewire → #10631 goes green.

@calebporzio
calebporzio merged commit 886d655 into main Aug 30, 2026
2 checks passed
@calebporzio
calebporzio deleted the claude/defer-tree-init branch September 7, 2026 11:44
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