问题
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