19. Cloak


Cloaking in Alpine is a mechanism to temporarily apply a style to an element before Alpine itself kicks in. Now that sounds really complicated, but this addresses a problem that we've seen throughout the series, and that is a flicker of content before Alpine kicks in to hide something. Let's take a look at an example just to refresh our memory.
So we're going to go ahead and create an element out here, really, really simple, and back to the basics that we've looked at that says open or show false. We know that with this we have an element inside of here which uses x-show, and that will only show if show is true, and this is the content here.
So let's go over and just have a look at what we get. Of course, we get that flicker that we've seen throughout the series. Now how do we address this? Well, we do this using x-cloak.
Now I'm going to apply this on its own to this element without applying any specific styling, and let's see what happens. There's no real difference here, but let's just see if we can catch what happens on this element here that we've applied cloak to. You might see that you get a flicker if you watch around this area of that x-cloak being applied.
Now what's happening with x-cloak is incredibly simple. When we apply x-cloak to an element, it just gets removed when Alpine initializes. So it's there before Alpine initializes, but once Alpine does initialize, cloak will be removed. How can this help us stop this flicker?
Well, what we can do is somewhere globally inside of our app apply styles to x-cloak, that attribute. Let's go ahead and do that now. We're going to set display to none, and we're going to make this important. So any element on the page that has the x-cloak attribute is never shown.
Now what this means is x-cloak will be removed once Alpine initializes, so this style will no longer apply. But this element will not be shown because show is set to false. Let's go over and see the difference. When I refresh the page, we don't get that flicker of information.
But because x-cloak has been removed, this style no longer applies. The visibility of this element is being controlled by show. So what we could do is implement a button to actually toggle this. So x on click, and let's say show equals true, and say show me.
That's still going to work because x-cloak no longer exists on this element, and like I said before, this style will no longer be applied. So a really simple thing with an Alpine that just gets removed, but this allows us to hook in this style to prevent flickering.
19 episodes2 hrs 10 mins


Alpine.js is a refreshingly minimal JavaScript framework that gives you the reactive nature of Vue and React, but with much more simplicity. This course will get you up to speed on how to use it, with plenty of practical examples along the way.

Alex Garrett-Smith
Alex Garrett-Smith
Hey, I'm the founder of Codecourse!


No comments, yet. Be the first to leave a comment.