Skip to content

[4.x] Defer Alpine init per-component while script module loads - #10295

Closed
joshhanley wants to merge 19 commits into
4.xfrom
josh/defer-alpine-init-minimal
Closed

joshhanley wants to merge 19 commits into
4.xfrom
josh/defer-alpine-init-minimal

Conversation

@joshhanley

Copy link
Copy Markdown
Member

Alternative to #9861 (Solution A). Same fixes, different approach: keeps Livewire.start() synchronous and confines the change to per-component _x_ignore juggling, rather than pre-loading all modules ahead of Alpine.start().

The Scenario

Alpine.data() registered inside a single-file component's <script> block isn't available when Alpine evaluates x-data on that component. The browser console shows:

Uncaught ReferenceError: testAlpineData is not defined

Happens on initial load, after wire:navigate, on dynamic child mounts, and when a #[Lazy] component hydrates.

<?php

new class extends Livewire\Component {
    //
};
?>

<div x-data="testAlpineData">
    <div x-text="message"></div>
</div>

<script>
    Alpine.data('testAlpineData', () => ({
        message: 'alpine-data-loaded',
    }))
</script>

The Problem

Alpine.start() walks the DOM synchronously, but component script modules are loaded via async import(). Alpine evaluates x-data="testAlpineData" before Alpine.data() has been registered.

The Solution

Defer Alpine initialisation on a per-component basis while that component's module is loading.

  • js/lifecycle.js — in interceptInit, if the new component's module is pending, set _x_ignore on the root, register a callback to clear it and Alpine.initTree(el) once the import resolves, and return early so wire: directive triggers fire on the re-init pass.
  • js/features/supportJsModules.js effect hook — for already-initialised components (lazy hydration / update), set _x_ignore on the live root before morph runs, then after the import clear _x_ignore and _x_marker and call Alpine.initTree.
  • js/features/supportJsModules.js interceptClone — Alpine's morph plugin runs cloneNode(from, to) which calls initTree(to) on the detached to element where _x_ignore on the live from doesn't reach. Mirror the flag onto to for any element under a component with a pending module.

Trade-off: a brief flash of uninitialised HTML between morph applying and the module resolving. Solution A avoided this by pre-loading modules upfront; this PR accepts it in exchange for a synchronous boot lifecycle.

Fixes #9591
Fixes #9830
Fixes #9737

…onents

Use `interceptMessage` to collect and pre-load script modules from both the
component's own `scriptModule` effect (for lazy-loaded components) and its
`childScriptModules` effect (for dynamically added children) before the morph
occurs. This ensures `Alpine.data()` registrations are available when Alpine
evaluates `x-data` attributes.
…e PHP side

Replace the PHP-side `childScriptModules` effect (which used an `on('mount')` hook
and `store()` to aggregate child module info on the parent) with JS-side scanning of
`payload.effects.html` for `wire:effects` attributes containing `scriptModule`.

This eliminates all PHP changes, handles deeply nested child components automatically,
and shares a `findModulesInElements()` helper with `preloadExistingModules`.

Also removes dead code in `$wire.js` (`assetIsPendingFor` always returns false) and
reverts an unused `skip` parameter in `lifecycle.js`.
Revert the JS HTML scanning approach back to the PHP-side `childScriptModules`
effect for better performance (avoids parsing the entire response HTML into a
temporary DOM tree).

Fix the nesting limitation: walk up the ancestor chain in the `on('mount')` hook
so that deeply nested components with scripts (e.g. A→B→C where both B and C have
scripts) all bubble their module info up to the requesting component.
These were added by this PR and nothing imports them.
Reverts the JS and PHP implementation for script module pre-loading
so we can re-implement with Solution A (`onPrepare` hook approach).
Tests and fixture files are preserved.
Adds a new `onPrepare` hook to the message interceptor system that
pre-loads script modules before `processEffects` runs, preventing the
race condition where `Alpine.data()` registrations aren't ready when
Alpine evaluates `x-data`.

Scenario 1 (initial load): `start()` is now async and awaits all module
imports before calling `Alpine.start()`.

Scenarios 2 and 3 (AJAX): `onPrepare` scans the response payload for
`scriptModule` effects and child modules in `effects.html`, imports
them into a shared cache, so the `effect` handler runs them synchronously.
Components with `Alpine.data()` in SFC script tags inside island
fragments weren't having their modules pre-loaded, causing
"not defined" errors when Alpine evaluated `x-data` synchronously
during the island morph.
Make `onSwap` callbacks promise-aware so script modules can be
pre-loaded between the DOM swap and Alpine re-initialisation.
Also adds `assertConsoleLogHasNoErrors()` to all script module tests.
Restores the JS code paths (supportJsModules, lifecycle, navigate,
request/*) to main so a different fix can be applied on top of the
existing test coverage.
…t-minimal

# Conflicts:
#	src/Features/SupportJsModules/BrowserTest.php
`Alpine.start()` walks the DOM synchronously, but component script
modules are imported asynchronously. When a component's template uses
`x-data="myComponent"` and the registration lives in its `<script>`
block, Alpine evaluates the `x-data` expression before `Alpine.data()`
has been called, producing "Can't find variable: myComponent".

Fix it on a per-component basis without making the boot lifecycle async:

  * `lifecycle.js` — when `interceptInit` creates a component whose
    module is pending, set `_x_ignore` on the root, register a callback
    to clear it and `Alpine.initTree(el)` once the import resolves, and
    return early so wire: directive triggers fire on the re-init pass
    instead of doubling up.

  * `supportJsModules.js` effect hook — when the module effect fires
    for an already-initialised component (lazy hydration / dynamic
    update), set `_x_ignore` on the live root before morph runs, then
    after the import clear both `_x_ignore` and `_x_marker` and call
    `Alpine.initTree` so the new `x-data` attribute morph added gets
    processed.

  * `supportJsModules.js` `interceptClone` — Alpine's morph plugin runs
    `cloneNode(from, to)` and initialises directives on the detached
    `to` element, where `_x_ignore` on the live `from` doesn't reach.
    Mirror the flag onto `to` for any element whose live counterpart
    sits under a component with a pending module.
@calebporzio

Copy link
Copy Markdown
Collaborator

Ok, I like this direction. I have some thoughts on the specifics of the implementation but overall this is the best move considering all the tradeoffs.

`interceptClone` now bails immediately unless a script module is
actually pending, instead of resolving a component for every element
morphed on every request. It also resolves ownership via
`findComponentByEl(from, false)` directly rather than
`.closest('[wire\:id]')`, so elements forwarded into a child through a
slot still defer to the component that actually owns them.

The import chain now uses `.finally()` for cleanup instead of only
`.then()`, so a failed script module import (e.g. a 404) no longer
leaves the component's directives permanently un-initialised.
component.el is set once in the Component constructor and never
reassigned, so the `component.el &&` checks were always true. Comments
are condensed to keep the non-obvious "why" without restating what the
surrounding code already makes clear.
@joshhanley
joshhanley marked this pull request as ready for review July 7, 2026 10:13
@joshhanley

Copy link
Copy Markdown
Member Author

@calebporzio ok sweet! I've push some changes to the PR and now it's ready for review.

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.

2 participants