Laravel Blade: What is best practice for adding javascript in blade files?
Asked Answered
F

3

5

I inherited a Laravel project that has many blade files with javascript inside tags within the blade file. The issue is that there is a lot of repetitive JS logic so I'd like to extract the JS and create JS files to include in the blade? Example: <script src="{{ asset('js/components/file.js')}}"></script> Is this the best practice for blade files or is it expected to be have the JS within the actual file?

Fathomless answered 19/4, 2019 at 6:11 Comment(0)
U
14

First you have to assign where yo want to push scripts in your layout. for example, say layout.blade.php is your main layout file and you want to inject codes after footer. So add

@stack('scripts')

after footer.

Now in your blade file, use @push to inject your code.

@push('scripts')
<script>
// your code
</script>
@endpush

check blade stack for further detail.

Unideaed answered 19/4, 2019 at 6:20 Comment(0)
W
3

if you use webpack.mix.js :

    mix.js('resources/js/app.js', 'public/js')
       .js('resources/js/my-super-amazing-script.js', 'public/js')

And in your main my-layout.blade.php :

    ...
        @yield('javascript')
    </body>

Then, in your specific page :

    @extend('my-layout.blade.php')
    ...
    @once
    @push('javascript')
        <script src="{{ mix('js/my-super-amazing-script.js') }}" defer></script>
    @endpush
    @endonce
Wellread answered 26/4, 2021 at 14:10 Comment(0)
I
2

I recommend you to maintain a specific section for page-specific javascript.

Please refer the following examples..

Example template.blade.php

  <body>

    @yield('content')

    @include('_partial.scripts')

    @yield('page-script')

    @include('_partial.footer')

</body>

then

@section('page-script')
<script type="text/javascript">
    // your custom script
</script>
@stop
Interrogative answered 19/4, 2019 at 16:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.