點燈坊

失くすものさえない今が強くなるチャンスよ

Using x-cloak to Prevent Page Flicker

Sam Xiao's Avatar 2022-01-13

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

cloak000

  • By clicking the Toggle button, Hello World would hide and show

  • When 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 is false by default, when <span>Hello World</span> is rendering, Alpine is not ready. So Hello World is shown
  • After Alpine finished loading, x-show is false. So Hello World is hidden

This is not our expected result. We want Hello World to be hidden until the Toggle button has clicked.

x-cloak

cloak000

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 with x-show

Reference

Alpine, x-cloak