Laravel blade use $(document).ready function

落爺英雄遲暮 提交于 2019-12-01 06:39:02

问题


I'm trying to use laravel blade templates including some javascript code into child view.

I have my mail app.blade.php file, where is placed string of jquery initialization:

<script src="/js/jquery.min.js"></script>

In my subview file settings.blade.php I want to use some jquery functions:

@extends('layouts.app')
@section ('content')
Settings main page
@endsection

<script type="text/javascript">
    $(document).ready(function() {
        alert("Settings page was loaded");
    });
</script>

But in browser console I get an error message Uncaught ReferenceError: $ is not defined which seems like jquery was loaded AFTER calling that function in subview file.

Adding a row: <script src="/js/jquery.min.js"></script> into settings.blade.php resolves the problem. But I dont want to add my script files into each of my subview file.

So question: how can I load main javascript\jquery files in parent blade file BEFORE loading subview files?


回答1:


Please follow this way

for jquery script file do this

<script src="{!!url('/js/jquery.min.js')!!}"></script>

and do this for content section

@extends('layouts.app')
@section ('content')
Settings main page

<script type="text/javascript">
    $(document).ready(function() {
        alert("Settings page was loaded");
    });
</script>

@endsection

Updated


Rather to scripting in content section, it would much better and professional way to create another section for scripting in app.blade.php

normally I follow this way

<html>
  <head> 
    @yield('page-style-files')
  </head>

  <body>
    <div class="wrapper">
     @yield('content')
    </div>
  </body>

  @yield('page-js-files')
  @yield('page-js-script')

<html>

so for example your code will look like this

@extends('layouts.app')
@section ('content')
  Settings main page    
@endsection

@section('page-style-files')
 <link href="....css" />
@stop


@section('page-js-files')
 <script src=".....js"></script>
@stop

@section('page-js-script')
<script type="text/javascript">
    $(document).ready(function() {
        alert("Settings page was loaded");
    });
</script>
@stop


来源:https://stackoverflow.com/questions/36736177/laravel-blade-use-document-ready-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!