Skip to content

[4.x] Defer Alpine start until script modules are pre-loaded - #9861

Closed
joshhanley wants to merge 12 commits into
mainfrom
josh/defer-alpine
Closed

joshhanley wants to merge 12 commits into
mainfrom
josh/defer-alpine

Conversation

@joshhanley

@joshhanley joshhanley commented Jan 29, 2026 •

Copy link
Copy Markdown
Member

The Scenario

When using Alpine.data() inside a single-file component's <script> block (or a multi-file component's co-located .js file), the registered Alpine data component is not available when Alpine processes the template. The browser console shows an error like:

Can't find variable: audioUploader

All Alpine expressions referencing the data component's properties fail silently.

<?php

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

<div x-data="audioUploader">
    <div x-show="dragging">Drop file here</div>
    <input type="file" x-on:change="file = $event.target.files[0]">
</div>

<script>
    Alpine.data('audioUploader', () => ({
        file: null,
        dragging: false,
    }))
</script>

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 dynamic import(), which means Alpine.data() registrations inside those modules execute after Alpine has already evaluated x-data attributes.

The sequence was:

  1. Alpine.start() walks the DOM synchronously
  2. Hits a [wire:id] element → Livewire interceptor creates the component → effect hook fires
  3. supportJsModules.js starts an async import() of the script module
  4. Alpine continues synchronously and evaluates x-data="audioUploader" → fails because Alpine.data() hasn't been called yet
  5. Module eventually loads and registers Alpine.data() — too late

The 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 calling Alpine.start(), it scans the DOM for all [wire:id] elements with scriptModule effects, imports their modules in parallel, and caches the resolved module objects in a Map.

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 calls run() synchronously. This means Alpine.data() is registered before Alpine evaluates x-data on 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 interceptMessage handler. When a server response arrives:

  • The component's own scriptModule effect is detected (for lazy-loaded components)
  • The parent's childScriptModules effect provides module info for any newly mounted children with scripts

The modules are imported immediately, and an async onEffect callback waits for all imports to complete before morph runs. This ensures Alpine.data() is registered before Alpine processes the new elements in the morphed DOM.

On the PHP side, a mount hook 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's childScriptModules effect.

Potential concerns

Initial boot delay: Livewire.start() is now async — it waits for all script modules to be fetched before calling Alpine.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

@joshhanley joshhanley changed the title Defer Alpine start until script modules are pre-loaded [4.x] Defer Alpine start until script modules are pre-loaded Jan 29, 2026
@calebporzio

Copy link
Copy Markdown
Collaborator

we need to think more about this one.

things we want:

  • as few as possible changes to the intiailzation lifecycle of livewire/alpine
    • so ideally fetching everything ahead of time and holding everything else up during that fetch

I bet there's some out of the box things we're missing here. idk...

@joshhanley
joshhanley marked this pull request as draft February 2, 2026 07:39
@joelstein

Copy link
Copy Markdown

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

@joelstein

Copy link
Copy Markdown

Can we do something similar to global styles?

<script global>
  // 
</script>

Or even:

<script alpine>
  // 
</script>

@joshhanley

Copy link
Copy Markdown
Member Author

@joelstein yeah use @assets or @script around your script tag and it should work.

…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.
@adamgoucher

Copy link
Copy Markdown

I believe the CSP build fails using the @script approach mentioned above. This

        <div x-data="leagueAutocompleter">

        </div>
        @script
            <script nonce="{{ Vite::cspNonce() }}">
                Alpine.data('leagueAutocompleter', () => ({
                    highlightedIndex: 0,
                }));
            </script>
        @endscript

got turned into

"(()=>{ Alpine.data('leagueAutocompleter', () => ({
                    highlightedIndex: 0,
                })); })()"

and errored with a CSP Parser Error.

Removing the @script gives the original reported behaviour of Alpine not defined and leagueAutocompleter not defined.

@calebporzio

Copy link
Copy Markdown
Collaborator

PR Review: #9861 — [4.x] Defer Alpine start until script modules are pre-loaded

Type: Bug fix
Verdict: Needs discussion

What's happening (plain English)

  1. User writes a single-file component (SFC) with a <script> block that calls Alpine.data('myComponent', ...) to register a reusable Alpine data component.
  2. The component's template uses x-data="myComponent" to reference that registration.
  3. Livewire's boot calls Alpine.start() synchronously. Alpine walks the DOM, hits x-data="myComponent", and tries to look it up — but the SFC's script module hasn't loaded yet because it's fetched via async import().
  4. Alpine throws "Can't find variable: myComponent". The script module eventually loads, but it's too late.

The root cause is a timing mismatch: Alpine.start() is synchronous, but SFC script modules load asynchronously.

Other approaches considered

  1. This PR's approach — pre-load all modules before Alpine.start(): Makes Livewire.start() async. Scans the DOM for all [wire:id] elements, parses their wire:effects and wire:snapshot attributes to extract module URLs, imports them all in parallel, then calls Alpine.start(). For subsequent requests (lazy/dynamic), uses interceptMessage + async onEffect to pre-load before morph. Pros: Guarantees modules run before Alpine processes directives. Cons: Delays Alpine start for ALL pages (even those without SFC scripts), complex ancestor-walking PHP logic for child modules, significant changes to the request lifecycle (making onEffect async, converting forEach to for...of loops).

  2. Use @script / @assets directives: As Josh noted in comments, wrapping in @script works for some cases. But a commenter pointed out this breaks CSP builds (the script gets stringified into an eval-like call). This is a workaround, not a fix — the SFC <script> block should work with Alpine.data().

  3. Simpler approach — defer Alpine.data evaluation: Instead of pre-loading modules, could we make Alpine tolerant of late Alpine.data() registrations? E.g., have x-data retry/defer when it encounters an unregistered name. This would require Alpine-side changes but would be zero-cost for pages without SFC scripts and wouldn't require making Livewire.start() async.

  4. Register a MutationObserver or Alpine interceptor: When a script module loads, re-initialize the relevant element subtree. Avoids blocking Alpine.start() entirely.

Code Review

Merge conflicts with main: The PR conflicts in two files:

  • js/request/index.js: Main introduced Alpine.transaction() wrapping around the success handler. The PR converts forEach to for...of and makes invokeOnEffect async. These need careful reconciliation.
  • src/Features/SupportJsModules/SupportJsModules.php: Main added isLazyLoadMounting/isLazyLoadHydrating awareness in dehydrate(). The PR simplified the condition. Main's logic needs to be preserved.

Concerns:

  1. Livewire.start() is now async (js/lifecycle.js:17). This is a significant change to the boot lifecycle. Every page pays the cost of preloadExistingModules() even if no components have script modules. The function parses wire:effects and wire:snapshot JSON attributes from the DOM — this is fragile and duplicates information that Livewire's component initialization already processes.

  2. DOM parsing to extract module info (supportJsModules.js:14-35): preloadExistingModules() manually queries [wire\\:id] elements, parses wire:effects JSON, then parses wire:snapshot JSON to get the component name. This is reaching into implementation details that could change. The component initialization already processes these attributes — this creates a parallel, unsynchronized code path.

  3. Ancestor-walking PHP logic (SupportJsModules.php:48-67): The on('mount') hook walks up the entire ancestor chain to push childScriptModules to every ancestor. This means if component A→B→C where C has a script, both A and B get the effect. This is O(depth) per mounted child with scripts, and stores references to parent components (mountParent) that could cause memory issues with deep nesting.

  4. onEffect is now async (message.js, interceptor.js, request/index.js): Making invokeOnEffect return a Promise and awaiting it changes the timing semantics of the entire request lifecycle. Every message interceptor's onEffect is now awaited via Promise.all. This is a broad change for a narrow use case. Other code relying on onEffect being fire-and-forget could break.

  5. forEach → for...of loop conversion (request/index.js:389-434): The PR converts the message/payload loops from forEach to for...of to support await. While functionally correct, this changes control flow semantics (continue vs return) and conflicts with main's Alpine.transaction() changes.

  6. Removed $js pending logic ($wire.js): The PR removes the assetIsPendingFor/runAfterAssetIsLoadedFor mechanism that handled $js calls during async module loading. Since modules are now pre-loaded, this is theoretically unnecessary — but if pre-loading ever fails or races, $js calls will silently return undefined instead of waiting.

  7. Style: JS uses let correctly (good). No semicolons (good). Follows project conventions.

Tests (BrowserTest.php:29-71):

  • Three tests added covering initial load, dynamic toggle, and lazy-loaded scenarios. Good coverage of the three scenarios described.
  • Test fixtures are clean and minimal.
  • However, I cannot verify these tests actually fail on main without the fix (environment issues prevented running tests).

Security

No 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.

Verdict

Needs 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:

  • Making Livewire.start() async affects every Livewire page
  • Making onEffect async changes the timing semantics of the entire request lifecycle
  • The DOM-parsing pre-load approach duplicates component initialization logic
  • The ancestor-walking PHP logic adds complexity for a narrow use case

Suggestion: Explore whether Alpine can be made tolerant of late Alpine.data() registrations (approach 3), or whether a MutationObserver-based re-init (approach 4) could solve this without touching the boot lifecycle. The laziest correct solution here might be on the Alpine side, not the Livewire side.

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

@mauritskorse

Copy link
Copy Markdown

@joelstein yeah use @assets or @script around your script tag and it should work.

Unfortunately this isn't a proper work around yet:

  • When having the script in the page we can't use import statements
  • When referencing a js file using @vite('form.js') or <script type="module" src="{{ Vite::asset('form.js') }}"></script> within @assets, the imports work, but it fails to load in time when using wire:navigate; direct loading of the page works though.

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.
@joshhanley

Copy link
Copy Markdown
Member Author

Alpine.data() Script Module Loading: Options

The Problem

Livewire v4 SFC/MFC components can have co-located JavaScript files. In SFCs, this is a <script> block; in MFCs, it's a separate .js file alongside the component class. These are compiled into ES modules served from /livewire/js/{component}.js and loaded dynamically via import().

Each script module typically contains Alpine.data() registrations:

// /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 x-data:

<div x-data="counter">
    <span x-text="count"></span>
    <button @click="increment">+</button>
</div>

The core issue: import() is asynchronous, but Alpine processes x-data synchronously. When Alpine encounters x-data="counter", it looks up "counter" in its registered data components. If the module hasn't loaded yet, "counter" isn't registered, and JavaScript throws a ReferenceError: "Can't find variable: counter".

This is different from @script/@endscript, which stores script content inline in wire:effects and evaluates it synchronously during the same effect hook. Script modules use dynamic import() because they're separate files served from a URL.

How it works today

On the PHP side, SupportJsModules.php adds a scriptModule effect (a hash of the file's modification time) during component dehydration. This hash is included in the component's wire:effects attribute in the HTML.

On the JS side, supportJsModules.js listens to the effect hook:

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 processEffects() in the Component constructor. But import() returns a promise; by the time it resolves, Alpine has already tried to evaluate x-data="counter" and failed.

The three scenarios

A complete solution must handle all three scenarios. In each case, the script module must be loaded and its Alpine.data() registration executed before Alpine evaluates x-data on that component.

Scenario 1: Initial page load. Components with script modules are present in the server-rendered HTML. Their modules must be loaded before Alpine.start() processes x-data on those components.

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 (wire:loading) must remain visible until the child's module is ready.

Why loading state matters

Solving 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 Alpine.start() adds a small delay to that process, but the user is already waiting for the page to become interactive. No special loading state management is needed.

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 wire:loading indicators on the parent for scenario 3. The morph is what removes this UI: it replaces the placeholder with the real component (scenario 2) or inserts the new child and clears loading indicators (scenario 3). If the morph applies before modules are ready, that UI disappears and the user sees broken, uninitialised content in its place.

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 pipeline

When a Livewire AJAX response arrives, processing happens per message (component) inside an Alpine.transaction:

Alpine.transaction {
    mergeNewSnapshot → onSync → processEffects → onEffect → await onMorph
} → onFinish → onRender

Key hooks:

  • processEffects is where module loading currently happens. The effect hook in supportJsModules.js fires and starts an async import(). The promise resolves sometime later.
  • onEffect is where wire:loading clears its indicators (wire-loading.js:106-112). Once onEffect runs, loading spinners disappear.
  • onMorph is where the DOM is updated. The morph replaces placeholders and inserts new children.

By the time the module's import() resolves, onEffect and onMorph have already run. Loading indicators are gone, the DOM has been updated, and the module arrives after the user has already seen broken content.

What a complete solution needs

  1. Scenario 1 (initial load): Modules must be loaded before Alpine processes x-data on page load.

  2. Scenario 2 (lazy components): Modules must be loaded before the morph replaces the lazy placeholder with the real component.

  3. Scenario 3 (dynamic children): Modules must be loaded before the parent's loading indicators are cleared and the morph inserts the new child.

  4. Error handling: If a module fails to load (network error, 404), the component should still initialise without the module's functionality. A partially working component is better than one that never appears. Log a console warning and continue.

  5. Timeout protection: Module imports that hang (slow CDN, broken URL) must not block response processing indefinitely. Use Promise.race with a reasonable timeout so the UI degrades gracefully rather than freezing.


Solution A: Livewire-Only (onPrepare)

No Alpine changes. All three scenarios handled in Livewire.

Scenario 1 (initial load): Make start() in lifecycle.js async. Before calling Alpine.start(), scan all [wire:id] elements on the page, parse their wire:effects for scriptModule hashes, import() all modules in parallel, and store them in a shared module cache. When Alpine.start() runs and the effect hook fires for each component, the module is already cached and module.run() executes synchronously.

Scenarios 2 and 3 (AJAX responses): Add a new awaitable onPrepare hook to Livewire's message interceptor system, positioned between onSync and processEffects:

onSync → onPrepare (awaited) → processEffects → onEffect → onMorph

A new hook is needed here because onSync is currently synchronous. Making onSync awaitable would be a breaking change for applications that expect it to execute synchronously. onPrepare is a new, dedicated async hook that doesn't change existing behaviour.

A handler in supportJsModules.js uses onPrepare to scan the response payload: the component's own effects.scriptModule and any child components found in effects.html (parsed via an inert <template> element, querying for [wire:effects] elements). All discovered modules are imported and cached before processEffects runs. Because onPrepare runs before onEffect, loading indicators and placeholders remain visible while modules load. By the time effects are processed, modules are cached and execute synchronously.

Shared module cache: Both mechanisms (initial pre-load and onPrepare) share a single Map in supportJsModules.js, keyed by component name + hash. The effect handler checks the cache first; if the module is cached, it runs synchronously and never creates a pending asset entry.

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
  • (+) onPrepare follows the existing interceptMessage pattern used by supportMorphDom, wire-loading, etc.
  • (+) Correct wire:loading and 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_ignore flag (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 onSync may 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:loading and placeholder timing
  • (-) Breaking change. onSync is currently synchronous. User-land code using onSync may 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.js has its own DOM insertion path (via effects.islandFragments and 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 preserves listeners, url, and scripts effects when caching a page, not scriptModule. Alpine.data() registrations persist globally, but $js actions 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.
@joshhanley

joshhanley commented Mar 13, 2026 •

Copy link
Copy Markdown
Member Author

Update: Islands and Navigate Support

Following 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.

Islands

When a component with Alpine.data() in its script tag appears inside an @island fragment, the module wasn't being pre-loaded because onPrepare only scanned effects.html. Island fragments come through as effects.islandFragments, which is a separate array of HTML strings.

Fix: The onPrepare handler now also scans each island fragment for nested components with script modules.

Navigate

When navigating to a new page via wire:navigate, preloadInitialModules() only runs once on initial page load. After navigate swaps the DOM and scripts load, Alpine.initTree() fires immediately, hitting the same race condition.

Fix: supportJsModules.js listens for alpine:navigating and registers an onSwap callback that returns the preloadInitialModules() promise. The navigate plugin now collects return values from onSwap callbacks (.map() instead of .forEach()) and awaits them with Promise.all() before calling nowInitializeAlpineOnTheNewPage(). This is backwards-compatible: existing sync onSwap callbacks return undefined, which Promise.all resolves immediately.

The module imports start as soon as the DOM is swapped (when the new [wire:id] elements are scannable), so they run in parallel with remote script loading. By the time we reach the await, they've likely already resolved.

Test Coverage

All scenarios now have browser tests with assertConsoleLogHasNoErrors():

  1. Initial page load (pre-existing)
  2. Dynamically added child component
  3. Lazy-loaded component
  4. Component inside an @island fragment (new)
  5. Navigate to a page with Alpine.data() component (new)
  6. Navigate between two pages that share the same Alpine.data() component (new, verifies module cache persists)

@joshhanley
joshhanley marked this pull request as ready for review March 13, 2026 11:20
@calebporzio

Copy link
Copy Markdown
Collaborator

I've been feeling pretty scared about merging this. Making Alpine.start() async makes me super nervous.

Here's a table made by AI comparing this solution with the simpler solution B:

CleanShot 2026-05-01 at 10 47 54@2x

Gonna have it throw together a PR and see how we feel about that. thanks everyone!

@calebporzio

Copy link
Copy Markdown
Collaborator

welp, the AI didn't throw together a PR lol. mind following up on this @joshhanley ? tyty

@joshhanley

Copy link
Copy Markdown
Member Author

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

@calebporzio

Copy link
Copy Markdown
Collaborator

Closing because of #10295

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.

5 participants