christiant's avatar

jQuery is not loading into project

Hi, I have tried to get jquery working but I am failing. I took the basic laravel installation that includes already bootstrap for the User/Login and just to be sure installed jquery again via npm

I included this in resources/js/app.js

//already there:
require('./bootstrap');
//new
import $ from 'jquery';
window.$ = window.jQuery = $;

and in webpack.mix.js this is all there is

const mix = require('laravel-mix');
   mix.js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css');

I run npm run dev but I add just like this

$( document ).ready(function() {
    console.log( "ready!" );
});

I get following error: $(document).ready(function() $ is not defined I tried $, jQuery, jquery but I seem to oversee something essential.

0 likes
3 replies
christiant's avatar

So what I found out after a few days of research: defer seems to cause to load the scripts at the end of the loading. and that is after my scripts

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

do you not have javascript in the blade-files? is there a better way to do it?

Snapey's avatar

I don't know another way other than wrapping my javascript in window.load by which time $ is available.

@section('page_script')
    <script>
        window.onload = function () {
            initMap();
            maps();
        };

    ....
@endsection

and then @yield('page_script') in my master layout

BTW jquery is already loaded in bootstrap.js make sure you are not including it twice

christiant's avatar

cheers, snapey. thanks for the double load advice.

I am currently in the state to use defer again. I added a section in my layout, at the bottom of the body

    <script type="text/javascript">
        window.onload = function () {
            @section('footer_js')

            @show
        };
    </script>

and with every blade I want to add js I do this

@section('footer_js')
    @parent
  <new_js_code>
@endsection

From security point it seems the browser-world is in favor of static js-files. however I do not need all the js snippets all the time. I hope at the end of the project I will see if I can refactor and maybe I will have a static js file that I can load (with defer)

Please or to participate in this conversation.