Search code examples
laravel-5turbolinks

Turbolinks JS structure


I am trying to use Turbolinks with my Laravel 5.2 application, there are some js errors, considering that some pages need extra JS. I can't figure out how to load the page specific JS what to load first(in the head section or after the content section ???)

here's my current master layout:

<!DOCTYPE html>
<html>
<head>
    <title>@yield('title')</title>
    <!-- Load CSS -->
    @include('assets.css')
    <!-------------->
    <!-- Load jQuery -->
    <script src="{{ URL::asset('js/jquery-2.1.4.min.js')}}"></script>
    <script src="{{URL::asset('js/jquery.turbolinks.min.js')}}"></script>
    <script src="{{URL::asset('js/jquery.address.js')}}"></script>
    @yield('head')
    <script src="{{ URL::asset('js/turbolinks.js')}}"></script>
    <!----------------->
</head>
<body>
<!-- Load Navbar -->
@include('elements.html.navbartop')
<!----------------->
<div class="pusher">

    <div id="content" class="ui main container" style="margin: 85px 0 50px 0">
        <!-- Load Content -->

        @yield('content')
        <!------------------>
    </div>
</div>
<!-- Load Footer -->
@include('elements.html.footer')
<!----------------->
<!---->
<script src="{{ URL::asset('js/semantic.min.js')}}"></script>
<!--------------------->
<script>
    @include('ajax.search') // searchbar ajax
</script>
</body>
</html>

now a different page:

@extends('layout.master')

@section('title', 'Dashboard')

@section('head')
<script>
    $(document).ready(function () {    

        $('element').dowhatever;
    });

</script>
@endsection

@section('content')
 ....
@endsection

Solution

  • Instead of using $(document).ready event, you should use the turbolinks load event like this:

    document.addEventListener("turbolinks:load", function() {
        $('element').dowhatever;
    });
    

    Also you need to understand the way that Turbolinks 5 works, because load and evaluate any script on the initial page load and then append to the current head element.