Skip to content Skip to sidebar Skip to footer

Laravel 5.4 Script Loading Issue

I'm working on my first Laravel project (5.4), actually I don't understand why my js script doesn't work like I expected. I use Mix and Blade : // webpack.mix.js let { mix } = requ

Solution 1:

I finally figure who was guilty : Mix (or the way I used Mix)

I wrongly believed that mix.js and mix.scripts was the same function. But mix.scripts only combine and minify files while mix.js also do compiling ECMAScript 2015 and module bundling. I don't really know why but it was a problem in my case.

mix.js(['public/js/admin.js',
    'public/js/dashboard.js'], 'public/js');

replaced by :

mix.scripts(['public/js/admin.js',
    'public/js/dashboard.js'], 'public/js/all.js');

See more : Laravel doc

Solution 2:

I had a similar issue, and the problem was that at the moment I was using jQuery for the first time, the app.js file generated by webpack wasn't loaded yet.

You can do a simple test to see if you have the same issue. In your first chunk of code where you use jQuery (the line of code that throws you the $ error), wrap that code in this:

document.addEventListener("DOMContentLoaded", function(event) { 
 // Your jQuery code
});

One workaround is to load app.js earlier in your blade main layout file, but I am sure it can be done in a better way. I am fairly new to Laravel, so I am still figuring out these kinds of things...

Edit:

Ok, I think I understood now how to do it properly:

  1. In your main blade layout (in my case app.blade.php), at the bottom right before the </body> tag, load your webpack script, all other external scripts you might load, and finally add a yield scripts section.

Example:

<scriptsrc="/js/app.js"></script><scriptsrc="other/scripts/that/you/need.js"></script>
@yield('scripts')
  1. In the blade template where you need jQuery code, instead of adding it directly in the content section, you create a new section called scripts.

Example:

@section('content')
//Your view code@endsection@section('scripts')
//Your jQuery code@endsection

That way, your jQuery code is loaded after the main layout has already loaded the webpack javascript file (which loads jQuery).

Solution 3:

Simply include js file as shown below in your blade files as in my case I'm including add-section.js which is placed inside public/js

<script src="{{ asset('/js/add-section.js') }}"></script>
@yield('scripts')

Post a Comment for "Laravel 5.4 Script Loading Issue"