If the default state of an x-show
on page load is false
, you may want to use x-cloak
on the page to avoid Page Flicker
.
Version
Alpine 3.9
x-show
By clicking the
Toggle
button,Hello World
would hide and showWhen refreshing the page,
Hello World
would show first and then hide
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://unpkg.com/alpinejs" defer></script>
<title>Alpine</title>
</head>
<body x-data="{ isShow: false }">
<button @click="isShow = !isShow">Toggle</button>
<div x-show="isShow">Hello World</div>
</body>
</html>
Line 9
<body x-data="{ isShow: false }">
<button @click="isShow = !isShow">Toggle</button>
<div x-show="isShow">Hello World</div>
</body>
- Although
isShow
isfalse
by default, when<span>Hello World</span>
is rendering, Alpine is not ready. SoHello World
is shown - After Alpine finished loading,
x-show
is false. SoHello World
is hidden
This is not our expected result. We want
Hello World
to be hidden until theToggle
button has clicked.
x-cloak
When refreshing the page, Hello World
is hidden.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://unpkg.com/alpinejs" defer></script>
<title>Alpine</title>
<style>
[x-cloak] {
display: none !important;
}
</style>
</head>
<body x-data="{ isShow: false }">
<button @click="isShow = !isShow">Toggle</button>
<div x-show="isShow" x-cloak>Hello World</div>
</body>
</html>
Line 14
<body x-data="{ isShow: false }">
<button @click="isShow = !isShow">Toggle</button>
<div x-show="isShow" x-cloak>Hello World</div>
</body>
x-cloak
: hide Hello World
when HTML is rendering with x-show
.
Line 9
[x-cloak] {
display: none !important;
}
Add [x-cloak]
to display: none !important;
to hide element.
Conclusion
x-cloak
is often used withx-show