Hundreds of founders, makers and marketers are part of The Digital Product Playbook.

This month we're giving away $700 of DigitalOcean credit, 1 year of SnapShooter along with a whole bunch of DigitalOcean goodies!

Join for free today at

Directive precedence in Alpine

Lots of people get caught out by the fact that Alpine evaluates each directive in a particular order. Let's look at the order it uses,

Published 5 months ago | Updated 5 months ago

Since Alpine doesn't have a virtual DOM and doesn't compile your templates, it evaluates a component's directives procedurally, in the order that they are defined.

Directive evaluation

When defining your directives on a component, the order does matter.

<div x-data="{ text: 'Hello' }">
    <p x-text="text" x-bind:style="color: red;"></p>

In the example above, our text will be set before the style attribute is updated. This could cause problems since you will see a flash of black, or whatever the default color is, before the x-bind:style directive is evaluated.

To counter this problem, you could swap the two directives around:

<div x-data="{ text: 'Hello' }">
    <p x-bind:style="color: red;" x-text="text"></p>

Now the x-bind:style is reached first, then our x-text directive is evaluated.

Another option would be adding x-cloak to the element, at the end.

<div x-data="{ text: 'Hello' }">
    <p x-text="text" x-bind:style="color: red;" x-cloak></p>

Now the <p> will be hidden (as long as you have the correct CSS) until Alpine has completely initialised the element.

If you're interested in the piece of code that handles all of the evaluation, you can find it here in the GitHub repository.