Repository navigation
[4.x] Defer Alpine init per-component while script module loads - #10295
Closed
joshhanley wants to merge 19 commits into
Closed
joshhanley wants to merge 19 commits into
joshhanley wants to merge 19 commits into
Conversation
…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.
joshhanley
marked this pull request as draft
May 18, 2026 07:12
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
marked this pull request as ready for review
July 7, 2026 10:13
Member
Author
|
@calebporzio ok sweet! I've push some changes to the PR and now it's ready for review. |
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.
Alternative to #9861 (Solution A). Same fixes, different approach: keeps
Livewire.start()synchronous and confines the change to per-component_x_ignorejuggling, rather than pre-loading all modules ahead ofAlpine.start().The Scenario
Alpine.data()registered inside a single-file component's<script>block isn't available when Alpine evaluatesx-dataon that component. The browser console shows:Happens on initial load, after
wire:navigate, on dynamic child mounts, and when a#[Lazy]component hydrates.The Problem
Alpine.start()walks the DOM synchronously, but component script modules are loaded via asyncimport(). Alpine evaluatesx-data="testAlpineData"beforeAlpine.data()has been registered.The Solution
Defer Alpine initialisation on a per-component basis while that component's module is loading.
js/lifecycle.js— ininterceptInit, if the new component's module is pending, set_x_ignoreon the root, register a callback to clear it andAlpine.initTree(el)once the import resolves, and return early so wire: directive triggers fire on the re-init pass.js/features/supportJsModules.jseffecthook — for already-initialised components (lazy hydration / update), set_x_ignoreon the live root before morph runs, then after the import clear_x_ignoreand_x_markerand callAlpine.initTree.js/features/supportJsModules.jsinterceptClone— Alpine's morph plugin runscloneNode(from, to)which callsinitTree(to)on the detachedtoelement where_x_ignoreon the livefromdoesn't reach. Mirror the flag ontotofor 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