Introduction
When using Alpine.js to control the visibility of elements, a brief flash of unstyled content (FOUC) can occur before Alpine.js initializes. This is especially noticeable on slower devices or when loading Alpine.js asynchronously. This post describes how to eliminate this flicker using a simple CSS rule.
The Problem: Modal Flash
Imagine a modal that should only be visible after Alpine.js has initialized. Without proper precautions, the modal might briefly appear in its default, unstyled state before Alpine.js takes over and hides it. On some browsers, notably Safari, this flash can even result in the modal becoming stuck and uncloseable if Alpine.js hasn't fully loaded.
The Solution: x-cloak and CSS
Alpine.js provides the x-cloak directive, which adds the attribute x-cloak to an element. We can then use CSS to hide elements with this attribute. The key is to ensure this CSS rule is applied early in the rendering process.
Here's the CSS rule:
[x-cloak] {
display: none !important;
}
And here's how you'd use it in your HTML:
<div x-data="{ open: false }" x-cloak>
<button @click="open = true">Open Modal</button>
<div x-show="open" @click.away="open = false">Modal Content</div>
</div>
With this setup, the <div> and its contents will be hidden by the CSS rule until Alpine.js removes the x-cloak attribute after initialization. The !important flag ensures that this style takes precedence over other conflicting styles.
Benefits
- Eliminates FOUC: Prevents the brief display of unstyled content.
- Improved User Experience: Creates a smoother, more professional appearance.
- Works Across Browsers: Provides a consistent experience regardless of browser or device.
Usage Notes
- Ensure the CSS rule is included in your main stylesheet or in a
<style>block in the<head>of your document. - Apply the
x-cloakattribute to the outermost element you want to hide. - Verify that Alpine.js is initialized correctly.
Key Insight
A small CSS rule combined with Alpine.js's x-cloak directive can significantly improve the perceived performance and overall polish of your web application by preventing the flash of unstyled content during page load.
Top comments (0)