I see a lot of people are not getting benefits from laravel blade fully. One of blade directive @stack('scripts')
is very helpful when you have javascript need to execute in the child page.
I create a fresh Laravel installation to demo an example. I have to make auth scaffolding with laravel/ui package because I'm using Laravel 6.
What is stack('anyname') directive
Stack directive as self-explaining it stacks the scripts where you want to stack them.
How to use
Let's say you have a master view and child views. And you have some javascript operations specifically related to child page may be an Ajax request. Now it is not good practice to put every javascript on the master page. It will slow down the speed because it is executing child pages scripts that don't need.
So what we need to do, in our master page just before closing body tag make @stack
like below code.
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" ></script>
@stack('child-scripts')
Now in our child page, let's say home, you have alert specific to the child, how to do that
@extends('layouts.app')
@section('content')
<div>I'm child</div>
@endsection
@push('child-scripts')
<script>
alert('I\'m coming from child')
</script>
@endpush
And alert is coming from child
My thoughts:
It is a very clean way of writing javascript.
It improves code readability and performance.
And it will always go to the end of the page as recommended where you put @stack
, directive does not matter from where push
is coming.
Top comments (6)
The problem with @stack and push is, you can replicate it.
When push would not end up repeating the same script, this would be a crazy powerfull tool.
You don't need to worry it at all. The issue won't happen while you are working with Laravel.🙂
Nice!
Nice!
hello, what is the difference if I put the script part at the end of the child blade view without the push directives?
Thank you.
It will render the script right where you call the child component. While push will make sure script is at the end of body always.