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?
$( document ).ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
The key difference between $(document). ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc.
Your answer There are three options: If script is the last tag of the body, the DOM would be ready before script tag executes. When the DOM is ready, "readyState" will change to "complete" Put everything under 'DOMContentLoaded' event listener.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With