How to include javascript files on specific pages with Blade in Laravel

Categorized as Laravel Tagged

There is a beautiful trick to make this happen with Laravel.

First, you need to specify @stack method in your main blade file (the wrapper) or in the file for javascript includes. Second, you need to “push” from your specific page the needed javascript include.

For example, we have this blade files structure:

  1. /views/main.blade.php, the wrapper for our pages
  2. /views/partials/javascript.blade.php, javascript file includes
  3. /view/posts/single.blade.php, blog post file, which has to have its own javascript file included
// views/main.blade.php

<!DOCTYPE html>





// views/partials/javascript.blade.php

<script defer src="[email protected]/dist/cdn.min.js"></script>
// views/partials/single.blade.php


<script defer src="[email protected]/dist/cdn.min.js"></script>




Now, your post page specific javascript is being pushed where it is needed and exists only on the blog pages. Enjoy!

Leave a reply

Your email address will not be published. Required fields are marked *