Use '@stack' & '@push' to push js file in blade.php

I am trying to push extra js file only in page.blade.php file.

for example
layouts/app.blade.php

<a class="sr-only focus:not-sr-only" href="#main">
  {{ __('Skip to content') }}
</a>

@include('sections.header')

  <main id="main" class="main">
    @yield('content')
  </main>

  @hasSection('sidebar')
    <aside class="sidebar">
      @yield('sidebar')
    </aside>
  @endif

@include('sections.footer')

@stack('scripts')

page.blade.php

@extends('layouts.app')

@section('content')
  @while(have_posts()) @php(the_post())
    @include('partials.page-header')
    @includeFirst(['partials.content-page', 'partials.content'])
  @endwhile
  <div class="text-xl text-blue-400">heyeyeye</div>
@endsection

@push('scripts')
  <script src="{{ asset('page.js') }}"></script>
@endpush

But the script tag ended up added under footer tag(It should be add after app.js has be called).

Is there anyway for me to push script tag in different blade.php file?

Sorry for my poor English.

1 Like

The app.js line is printed by the wp_footer() call in index.php, which wraps the content that Blade generates: you won’t be able to use @push to put content there.

If you want to enqueue scripts only on a particular template, I’d recommend using wp_enquque_script() with a conditional, i.e.

if (is_page()) {
  wp_enqueue_script('page-js', 'page.js', [ 'app' ], false, true);
}

For anyone looking for general info on Blade @stacks, check out this post from a few years ago: