The best way to use x-cloak in Alpine JS
To give you an easy explanation: x-cloak will be removed after Alpine JS initializes. Understood everything? But if you are still asking yourself why is this important - keep reading.
Author: Markus A. Wolf
Updated: February 2024

First: specify attribute

First, it is possible to style HTML elements that have a specific attribute or attribute value and it looks like this: [attribute].

This selector is used to select elements with a specified attribute. So with this selector you are able to define some CSS for every HTML tag having this x-cloak attribute.

Imagine you have a script in AlpineJS that fetches some data from an API and if the request was successful it will be shown on the screen. What will be shown before the data was fetched? What will be shown before the data can be fetched? Wouldn’t it be nice to have a way to show this HTML only if you can give some feedback to the user - like loading, error and success?

With x-cloak you can define a CSS like the following so the script will only be shown after AlpineJS was initialized. This means you can start with a loading animation and this animation will be the first HTML a user sees of your script. After AlpineJS is initialized everything is ready to go. Every method and param is working. Nobody wants to see HTML code before it gets rendered and filled with content.

Second: The Key Changing Technique

<head>
    <!-- DEFINITIONS -->
    <style>
        [x-cloak] {
            display: none;
        }
    </style>
</head>
<body>
    <div x-data=”object” x-init=”function()” x-cloak >
    <!-- HTML -->
    </div>
</body>

If you have a fixed or defined height of your Alpine JS script / HTML and you don’t want to have a lot of “jumping” on your page replace display: none with: visibility: hidden.

<head>
    <!-- DEFINITIONS -->
    <style>
        [x-cloak] {
            visibility: hidden;
            overflow: hidden
        }
    </style>
</head>
<body>
    <div x-data=”object” x-init=”function()” x-cloak >
    <!-- HTML -->
    </div>
</body>

Alpine.js version 3

Since Alpine.js there is no need for x-init anymore so you can use x-cloak even more reduced.

<head>
    <!-- DEFINITIONS -->
    <style>
        [x-cloak] {
            display: none;
        }
    </style>
</head>
<body>
    <div x-data=”object” x-cloak >
    <!-- HTML -->
    </div>
</body>

All links in a practical list

More articles

Thoughts, topics or just solutions I would like to make available to you, colleagues and fellow enthusiasts.