How to fix $ is not defined in Laravel – 3 different Solutions

Errors like $ or jQuery are not defined happen when working with Laravel projects. These errors happen when working on a project which relies on jQuery. I encountered such an error while working on a project where I needed jQuery. So I am adding a solution here, which will help anyone facing such an issue.

Sometimes this error happens all of the sudden. Even your application might be running smooth and the next day you will start facing this issue, that $ or jQuery is not defined.

There might be different reasons which starts causing this issue in your Laravel application, as you can see the errors in below screenshot, stating Uncaught ReferenceError: $ is not defined.

In this tutorial of Laravel, We will show you 3 different approaches or solutions which can help you fix Uncaught ReferenceError: $ is not defined.

1. Remove Defer

Try removing defer attribute will fix this issue for you. You need to edit app.blade.php file and remove defer from the script.

File location: ->app.blade.php

   //this is wrong
   <script src="{{ asset('js/app.js') }}" defer></script>
   
   //this is correct
   <script src="{{ asset('js/app.js') }}" ></script>

This solution works, but our recommendation to adopt this solution is for an application which is using basic JavaScript code. In case you are using advanced JavaScript implementation via Vue.js or React, removing defer can cause some serious problems.

2. Import jQuery

Another solution to this problem is, we can try importing jQuery in a slightly different way. We need an app.js file and make changes as mentioned below.

File location: ->resources>js>app.js

window.$ = require("jquery")
window.bootstrap = require("bootstrap");

or

window.$ = window.jQuery = require('jquery');

3. Calling jQuery, when page is ready

One of the common reasons for this error is, we call jQuery or $ before the page is ready. This means the jQuery does not load completely and we call $ or jQuery. We can make our call to jQuery await by adding an event listener which for sure will fix this issue.

<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Your jquery code            
        alert('JQuery is ready!');            
    });
</script>

Conclusion

The purpose of using “defer” is to execute the script after the page is parsed. “defer” attribute will enable us to use the script only when the page loads completely.

2 thoughts on “How to fix $ is not defined in Laravel – 3 different Solutions”

Leave a Comment