RahmaniLara's avatar

Livewire @script load before @assets

I have Livewire page and I'm using assets

@assets @vite('resources/js/phone.js')

@endassets

And I use script tag

@scripts

console.log("hello")

@endscripts

The issue I'm facing that the script load before the assets

So in console I see hello before the phone.js loaded

0 likes
2 replies
LaryAI's avatar
Level 58

It seems like you're trying to ensure that your custom script runs after Livewire's assets and your phone.js file have loaded. Livewire provides directives to inject assets and scripts at specific points in your document. To ensure that your custom script runs after Livewire's assets and your phone.js file, you should place your script within the @livewireScripts directive or after it.

Here's how you can adjust your code:

<!-- Place Livewire styles in the head -->
<head>
    ...
    @livewireStyles
</head>
<body>
    ...
    <!-- Your Livewire components will go here -->
    ...

    <!-- Include Livewire scripts and then your custom scripts -->
    @livewireScripts

    <!-- Include your Vite assets -->
    @vite('resources/js/phone.js')

    <!-- Your custom script -->
    <script>
        document.addEventListener('livewire:load', function () {
            // This will ensure that your script runs after Livewire is fully loaded
            console.log("hello");
        });
    </script>
</body>

By using the livewire:load event, you ensure that your custom script runs after Livewire has finished loading its assets. This should resolve the issue of your script executing before phone.js is loaded.

If you're not using Livewire's scripts and you're manually including phone.js with Vite, you can use the defer attribute on your script tag to defer its execution until after the document has been parsed:

<!-- Include your Vite assets -->
@vite('resources/js/phone.js')

<!-- Your custom script with defer attribute -->
<script defer>
    console.log("hello");
</script>

The defer attribute tells the browser to execute the script after the document has been parsed but before firing the DOMContentLoaded event, which should also ensure that your phone.js is loaded first.

RahmaniLara's avatar

In livewire document they write if you use @assets directive livewire will insure that @assets will execute before @script . In my page update.blade.php it show

@assets @vite('ressources/js/phone.js')

@endassets

@script

Console.log("hello")

@endscript

All this in page update.blade.php but in Console it show hello first is there's alternative way to do that or way to fix it

1 like

Please or to participate in this conversation.