Skip to content
Advertisement

How to use defer and make JS plugin working as well

When I use defer on app.js, there is a js plugin not working properly.

If I remove defer, although the plugin works, but there is a warning to ask me to use defer, and I don’t know what to do.

// resource/js/app.js
require('./bootstrap');

import Alpine from 'alpinejs';

import mask from '@alpinejs/mask'
Alpine.plugin(mask);

window.Alpine = Alpine;
Alpine.start();

// webpack.mix.js
mix.js('resources/js/app.js', 'public/js').postCss('resources/css/app.css', 'public/css', [
    require('tailwindcss'),
    require('autoprefixer'),
]);

This is the test.blade.php

<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <title>title</title>

    <link rel="stylesheet" href="{{ asset('css/app.css') }}">
    <livewire:styles />
    <livewire:scripts />    
    <script src="{{ asset('js/app.js') }}"  defer></script>
</head>

<body>
    <input x-mask="99/99/9999" placeholder="MM/DD/YYYY">
</body>
</html>

If I use <script src="{{ asset('js/app.js') }}" defer></script>, then the x-mask plugin will not working.

If I remove defer and use <script src="{{ asset('js/app.js') }}" ></script>, the x-mask works, but there is a warning Alpine Warning: Unable to initialize. Trying to load Alpine before is available. Did you forget to adddeferin Alpine's tag? on the chrome browser console.

What should I do? Any suggestion? Thank you!

Advertisement

Answer

Thanks to @Dauros, it works after I put an x-data directive to a parent element. (I also put the defer to the app.js)

<div x-data="{ date: '' }">
    <input x-mask="99/99/9999" placeholder="MM/DD/YYYY" x-model="date">
</div>
<script src="{{ asset('js/app.js') }}" defer></script>

It doesn’t mention on the alpineJS x-mask plugin page.

And I finally understand what the document said about the x-data in the Start Here and x-data.

Everything in Alpine starts with the x-data directive.

Everything in Alpine starts with an x-data directive. Inside of x-data, in plain JavaScript, you declare an object of data that Alpine will track.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement