2018-03-28 16:23
浏览 126

Laravel 5.6 - 我是否需要包含JQuery或者是否已经包含在app.js中?

I have created a Laravel 5.6 project on my local.

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

In one of the views, I tried

<script type="text/javascript">


        jQuery( "#ddtype" ).change(function() {
            alert( "Handler for .change() called." );



but it gives me jQuery is not defined error

If I try Bootstrap 4's collapse function, it works fine. Does that mean jQuery is already included?

I have done npm install and npm run dev

My resources/js/app.js requires bootstrap.js which looks like (not full code but top few lines) as below

window._ = require('lodash');
window.Popper = require('popper.js').default;

 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.

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

} catch (e) {}

Please advise. I have checked in different browsers to make sure no cache issues etc.


My layouts/app.blade.php structure is like this -

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

    <div id="app">


        <main class="py-4">


and myview.blade.php


    <script type="text/javascript">


            jQuery( "#ddtype" ).change(function() {
                alert( "Handler for .change() called." );


  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • du4629 2018-03-28 18:13

    jQuery loaded via your app.js, which is only loaded once the page is ready because of the defer attribute in your script tag.

    Your inline script tag where you call jQuery(document).ready is loaded as the page renders, therefore executed before the app.js has been loaded. Hence the error, since jQuery is not yet loaded at that time.

    To fix it, simply remove the defer attribute from the script tag.

    The defer attribute is a boolean attribute.

    When present, it specifies that the script is executed when the page has finished parsing.

    For more information about the defer attribute: https://www.w3schools.com/tags/att_script_defer.asp

    打赏 评论

相关推荐 更多相似问题