Repository navigation
[4.x] Defer Alpine start until script modules are pre-loaded - #9861
joshhanley wants to merge 12 commits into
Conversation
|
we need to think more about this one. things we want:
I bet there's some out of the box things we're missing here. idk... |
|
@joshhanley I'm looking for an elegant way to define an Alpine data component in my Livewire component without a huge x-data string. Any workaround until this pull request lands? |
|
Can we do something similar to global styles? Or even: |
|
@joelstein yeah use |
…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.
|
I believe the CSP build fails using the <div x-data="leagueAutocompleter">
</div>
@script
<script nonce="{{ Vite::cspNonce() }}">
Alpine.data('leagueAutocompleter', () => ({
highlightedIndex: 0,
}));
</script>
@endscriptgot turned into "(()=>{ Alpine.data('leagueAutocompleter', () => ({
highlightedIndex: 0,
})); })()"and errored with a CSP Parser Error. Removing the |
PR Review: #9861 — [4.x] Defer Alpine start until script modules are pre-loadedType: Bug fix What's happening (plain English)
The root cause is a timing mismatch: Other approaches considered
Code ReviewMerge conflicts with main: The PR conflicts in two files:
Concerns:
Tests (
SecurityNo security concerns identified. The changes don't touch hydration, synthesizers, or the request/response security boundary. Module URLs are derived from component names using the existing encoding scheme. VerdictNeeds discussion. Caleb's comment captures it well: "we need to think more about this one." The core problem is real and well-understood, but the solution's blast radius is too large:
Suggestion: Explore whether Alpine can be made tolerant of late Zero community reactions on the PR. Three linked discussions show real user pain, but the fix should match the narrowness of the problem. Reviewed by Claude |
Unfortunately this isn't a proper work around yet:
|
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.
Alpine.data() Script Module Loading: OptionsThe ProblemLivewire v4 SFC/MFC components can have co-located JavaScript files. In SFCs, this is a Each script module typically contains // /livewire/js/counter.js
export function run($wire) {
Alpine.data('counter', () => ({
count: 0,
increment() { this.count++ }
}))
}The component's Blade template references this registration via <div x-data="counter">
<span x-text="count"></span>
<button @click="increment">+</button>
</div>The core issue: This is different from How it works todayOn the PHP side, On the JS side, on('effect', ({ component, effects }) => {
let scriptModuleHash = effects.scriptModule
if (scriptModuleHash) {
let path = `${getModuleUrl()}/js/${encodedName}.js?v=${scriptModuleHash}`
pendingComponentAssets.set(component, Alpine.reactive({
loading: true,
afterLoaded: [],
}))
import(path).then(module => {
module.run.call(component.$wire, component.$wire, component.$wire.js)
pendingComponentAssets.get(component).loading = false
pendingComponentAssets.get(component).afterLoaded.forEach(callback => callback())
pendingComponentAssets.delete(component)
})
}
})The effect hook fires during The three scenariosA complete solution must handle all three scenarios. In each case, the script module must be loaded and its Scenario 1: Initial page load. Components with script modules are present in the server-rendered HTML. Their modules must be loaded before Scenario 2: Lazy/deferred components. A lazy component renders a placeholder first. The real component (with its script module) arrives via AJAX. The module must be loaded before the morph replaces the placeholder with the real component. Scenario 3: Dynamically added components. A parent re-renders and its new HTML includes a child component that wasn't there before. The child's module must be loaded before the morph inserts the child into the DOM and Alpine initialises it. The parent's loading indicators ( Why loading state mattersSolving the race condition isn't just about preventing crashes; modules need to be ready before the user sees the component. For scenario 1 (initial page load), this is straightforward. The page is loading anyway; the user expects to wait for Livewire to initialise. Loading modules before calling For scenarios 2 and 3, loading state is critical. In both cases, the user is looking at the page and waiting for something to appear. There's existing UI that communicates "something is happening": lazy placeholders for scenario 2, and The goal is to keep placeholders and loading indicators visible while modules load, then apply the morph once everything is ready. The user sees a continuous loading experience: placeholder or spinner, then the fully initialised component. No flash of broken content. Where module loading currently sits in the request pipelineWhen a Livewire AJAX response arrives, processing happens per message (component) inside an Key hooks:
By the time the module's What a complete solution needs
Solution A: Livewire-Only (
|
| Files changed | What changes |
|---|---|
supportJsModules.js |
Module cache, preloadInitialModules() export, onPrepare handler, updated effect handler with cache check and error handling |
lifecycle.js |
Async start() with await preloadInitialModules() |
interceptor.js |
Add onPrepare hook to MessageInterceptor |
message.js |
Add invokeOnPrepare(), expose onPrepare in invokeOnSuccess |
request/index.js |
await message.invokeOnPrepare() between invokeOnSync and processEffects |
Alpine changes: None.
Trade-offs:
- (+) No Alpine changes required
- (+) No breaking changes to existing hooks
- (+)
onPreparefollows the existinginterceptMessagepattern used bysupportMorphDom,wire-loading, etc. - (+) Correct
wire:loadingand placeholder timing - (-) Adds a new lifecycle hook (
onPrepare) to the message interceptor API
Solution B: Minimal Fix (deferred init only)
The smallest possible change. No pre-loading, no new hooks, no module cache. Just defer Alpine's initialisation of any component whose module is still loading, and re-initialise when it arrives.
In lifecycle.js's interceptInit, after creating a Component, check if its module is still loading and defer if so:
let component = initComponent(el)
if (assetIsPendingFor(component)) {
el._x_ignore = true
skip()
runAfterAssetIsLoadedFor(component, () => {
if (!el.isConnected) return
delete el._x_ignore
Alpine.initTree(el)
})
return
}No double-init occurs because _x_marker is never set when _x_ignore is truthy (Alpine's initTree only assigns _x_marker when _x_ignore is falsy), so re-init proceeds as if the element is new. The interceptInit callback skips Component creation on re-init because el.__livewire already exists.
This stops all crashes across all three scenarios. However, it doesn't solve the user experience:
- Scenario 1: Components flash as uninitialised HTML until their module loads, then re-init and become interactive.
- Scenarios 2 and 3: The morph applies immediately (removing placeholders and clearing loading indicators), then the child component sits in the DOM uninitialised until its module loads and re-init fires. The user sees a brief flash of inert content.
| Files changed | What changes |
|---|---|
lifecycle.js |
~15 lines in interceptInit: check assetIsPendingFor(), set _x_ignore, register re-init callback |
Alpine changes: None.
Trade-offs:
- (+) Smallest possible change; single file, ~15 lines
- (+) No new hooks, no module cache, no pre-loading logic
- (+) Stops all crashes immediately
- (-) FOUC on all three scenarios
- (-) Loading indicators and placeholders are not preserved (scenarios 2 and 3)
- (-) Uses Alpine's internal
_x_ignoreflag (undocumented; mitigated by maintaining both projects)
Solution C: Livewire-Only, No New Hooks (awaitable onSync)
Same approach as Solution A but without adding a new hook. Instead of onPrepare, make the existing onSync hook awaitable.
Scenario 1 (initial load): Same as Solution A. Make start() async, pre-import all modules before Alpine.start(), shared module cache.
Scenarios 2 and 3 (AJAX responses): onSync already runs between snapshot merging and processEffects, which is exactly where module pre-loading needs to happen. Make invokeOnSync() async so it awaits all onSync callbacks. A handler in supportJsModules.js registers on onSync to scan the response payload, discover modules, and import them before processEffects runs. Same module discovery logic as Solution A (parsing effects.html via inert <template> element). Same correct loading/placeholder timing.
The only internal user of onSync is supportPreserveScroll.js, which is synchronous and unaffected by the change.
While Livewire internals are unaffected, user-land code using
onSyncmay expect it to execute synchronously. Making a sync hook awaitable is a subtle contract change that could affect timing expectations in existing applications.
| Files changed | What changes |
|---|---|
supportJsModules.js |
Module cache, preloadInitialModules() export, onSync handler for module pre-loading, updated effect handler with cache check and error handling |
lifecycle.js |
Async start() with await preloadInitialModules() |
interceptor.js |
Change onSync default to async () => {} |
message.js |
Make invokeOnSync() async with Promise.all |
request/index.js |
await message.invokeOnSync() |
Alpine changes: None.
Trade-offs:
- (+) No Alpine changes
- (+) No new lifecycle hooks (smallest API surface change)
- (+) Correct
wire:loadingand placeholder timing - (-) Breaking change.
onSyncis currently synchronous. User-land code usingonSyncmay not expect it to be awaited. Making a sync hook async is a subtle contract change that could affect timing expectations. - (-) Changes the documented contract of
onSync
Recommendation
Solution A is the right approach. It handles all three scenarios correctly:
Scenario 1 (initial load): Making start() async and awaiting all module imports before calling Alpine.start() guarantees that every Alpine.data() registration is in place before Alpine walks the DOM. The user is already waiting for the page to become interactive, so the small additional delay is invisible.
Scenario 2 (lazy components): The onPrepare hook discovers and imports child modules before processEffects runs. Because onPrepare fires before onEffect and onMorph, the lazy placeholder stays visible while modules load. Once modules are cached, the morph applies and the fully initialised component replaces the placeholder in one step. No flash of broken content.
Scenario 3 (dynamic children): Same mechanism. The parent's wire:loading indicators remain visible while onPrepare loads the new child's module. The morph only applies after modules are ready, so the user sees loading spinner, then the complete child. No intermediate state where loading indicators have cleared but the child isn't initialised.
The new onPrepare hook follows the existing interceptMessage pattern used by supportMorphDom, wire-loading, and others. It doesn't change any existing hook contracts and requires no Alpine changes. From Alpine's perspective, module loading becomes fully synchronous: by the time processEffects runs and the effect hook fires, every module is already cached and module.run() executes immediately.
Solution C achieves the same result but introduces a breaking change by making onSync awaitable. Solution B stops the crashes but doesn't solve the user experience (FOUC on all three scenarios, loading indicators clear too early).
Solution B could be layered on top of A as a defensive fallback (if a module somehow isn't pre-loaded, the _x_ignore check catches it instead of crashing), but shouldn't be necessary if the pre-loading is solid.
Known areas needing verification
- Islands:
supportIslands.jshas its own DOM insertion path (viaeffects.islandFragmentsand streamed chunks) that may bypass the normal morph pipeline. Module discovery needs to account for this or be tested against it. wire:navigate:inscribeSnapshotAndEffectsOnElement(component.js) only preserveslisteners,url, andscriptseffects when caching a page, notscriptModule. Alpine.data() registrations persist globally, but$jsactions bound to the component instance may be lost on navigate cache restore. Needs testing.
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.
Update: Islands and Navigate SupportFollowing on from the options document I posted earlier, I've implemented solution A and extended it to cover two additional scenarios that weren't originally verified: islands and wire:navigate. IslandsWhen a component with Fix: The NavigateWhen navigating to a new page via Fix: The module imports start as soon as the DOM is swapped (when the new Test CoverageAll scenarios now have browser tests with
|
|
welp, the AI didn't throw together a PR lol. mind following up on this @joshhanley ? tyty |
|
@calebporzio theres a WIP PR here #10295. Have a look and let me know if you like the general direction and I will polish it. |
|
Closing because of #10295 |

The Scenario
When using
Alpine.data()inside a single-file component's<script>block (or a multi-file component's co-located.jsfile), the registered Alpine data component is not available when Alpine processes the template. The browser console shows an error like:All Alpine expressions referencing the data component's properties fail silently.
The Problem
Livewire's boot sequence calls
Alpine.start()synchronously, which walks the DOM and processes all directives immediately. Component script modules are loaded via async dynamicimport(), which meansAlpine.data()registrations inside those modules execute after Alpine has already evaluatedx-dataattributes.The sequence was:
Alpine.start()walks the DOM synchronously[wire:id]element → Livewire interceptor creates the component → effect hook firessupportJsModules.jsstarts an asyncimport()of the script modulex-data="audioUploader"→ fails becauseAlpine.data()hasn't been called yetAlpine.data()— too lateThe Solution
This handles three scenarios: initial page load, lazy-loaded components, and dynamically added children.
Scenario 1: Initial page load
Livewire.start()is now async. Before callingAlpine.start(), it scans the DOM for all[wire:id]elements withscriptModuleeffects, imports their modules in parallel, and caches the resolved module objects in aMap.When the effect hook fires during component creation (which happens inside Alpine's
interceptInit, before Alpine processes directives on the element), the handler finds the module in the pre-loaded cache and callsrun()synchronously. This meansAlpine.data()is registered before Alpine evaluatesx-dataon the same element.Scenarios 2 & 3: Lazy-loaded and dynamically added components
For components added after the initial page load (either lazy-loaded components or children dynamically added by a parent), the script modules are pre-loaded via an
interceptMessagehandler. When a server response arrives:scriptModuleeffect is detected (for lazy-loaded components)childScriptModuleseffect provides module info for any newly mounted children with scriptsThe modules are imported immediately, and an async
onEffectcallback waits for all imports to complete before morph runs. This ensuresAlpine.data()is registered before Alpine processes the new elements in the morphed DOM.On the PHP side, a
mounthook walks up the ancestor chain so that deeply nested components with scripts (e.g. A→B→C) all bubble their module info up to the requesting component'schildScriptModuleseffect.Potential concerns
Initial boot delay:
Livewire.start()is now async — it waits for all script modules to be fetched before callingAlpine.start(). The modules are imported in parallel, so the delay is bounded by the slowest module rather than the sum, but on pages with many SFC/MFC components with scripts, this could noticeably delay Alpine's initialisation.Fixes: #9591
Fixes: #9830
Fixes: #9737