Laravel Livewire 3, inline scripts do not work, no error, doesnt trigger event

682 views Asked by At

New to Livewire 3 and needing to use inline javascripts but its not working.

on my layout.blade.php , i have added stack('scripts')

on my livewire component partial i have added

@push('scripts')
<script>
    document.addEventListener('livewire:init', function () {
     console.log('loaded');
      });
</script>
@endpush

I also tried other events like livewire:initialize, livewire:load, DOMContentLoaded but still doesnt work.

I have been here for a few hours trying to solve this basic inline javascript. can anyone please help me?

2

There are 2 answers

0
gjg2013 On

I was using laravel livewire 3.1 and for some reason this was the cause of the issue. using

@script 
<script>
     console.log('loaded');
</script>
@endscript 

didnt work, it only displayed them in the browser as litereal @script and @endscript words

updating livewire to 3.3 solved this.

0
Sabin Chacko On

For me I did the mistake of putting @stack('scripts') in the <body> of app.blade.php

So I had to move it to the <head> part

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.bunny.net">
    <link href="https://fonts.bunny.net/css?family=figtree:400,500,600&display=swap" rel="stylesheet" />

    <!-- Scripts -->
    @vite(['resources/css/app.css', 'resources/js/app.js'])
    @stack('styles')
    @stack('scripts')
</head>

Then it started working!