The x-defer directive
The x-defer directive is a custom YSCP Alpine.js plugin that allows deferring the initialization of Alpine components.
The attribute is placed on the same element that also holds the x-data directive.
The value determines when the component will be initialized. Possible values are:
intersectinteractidleevent:eventname
Deferring the initialization of components that are not needed immediately can increase the interactivity of a page and reduce the main thread blocking time. Used correctly it will improve the core web vitals score.
The type of trigger to choose depends on the component.
What components can be deferred?
Depending on when a component is initialized, some common events may be missed, since event subscribers won't be called until the component is initialized.
The most common scenario is components requiring access to the customer section data missing the private-content-loaded event.
A possible workaround is to dispatch the reload-customer-section-data event in the components init method.
This will cause the private-content-loaded event to be dispatched again, and this time the component is able to receive it.
For example:
<div
x-data="{cart: null}"
x-defer="intersect"
x-init="$dispatch('reload-customer-section-data')"
@private-content-loaded="cart = $event.details.data.cart"
>
Values for x-defer
Intersect
This is the most common x-defer type. It will hold off initializing a component until it enters the viewport.
If it is in the viewport at the time the page loads, it will be initialized immediately.
<div x-data x-defer="intersect">
<span x-text="`This component is initialized when it enters the viewport.`"></span>
</div>
Interact
This x-defer value will initialize a component as soon as a user interacts with the page, that is, one of the touchstart, mouseover, wheel, scroll, or keydown events is dispatched.
<div x-data x-defer="interact">
<span x-text="`This component is initialized on user interaction.`"></span>
</div>
Idle
The component will be initialized at the convenience of the browser via window.requestIdleCallback.
A timeout can be set in the system configuration after which the component will be initialized in case the browser does not trigger the callback.
The default timeout is 4000ms.
<div x-data x-defer="idle">
<span x-text="`This component is initialized when the browser is idle or after 4s.`"></span>
</div>
event:eventname
By specifying an event:prefix, component initialization can be deferred until arbitrary events.
The event is observed on the window object.
<div x-data x-defer="event:toggle-cart">
<span x-text="`This component is initialized when the toggle-cart event is dispatched.`"></span>
</div>
Injecting x-defer rules through backend configuration
To enhance core web vitals in existing custom themes with minimal effort, useful defer rules are automatically injected into components based on configurable selectors. Further configuration details can be found in this section.