Summer Sale! All accounts are 50% off this week.

catalin560's avatar

how do you guys organize your assets?

Like how do you make sure your javascript loads only on the pages you need it?

0 likes
10 replies
manelgavalda's avatar

The typical thing to do is to add @yield('scripts') in your layouts/app view, so then you can always add the javascript with a section in each page.

app.blade.php

....
        @yield('scripts')
    </body>
</html>

another-view.blade.php

@section('scripts')
    <script>
    //
   </script>
@endsection
manelgavalda's avatar

In the documentation it uses @yield('content') and @section('content') as an example, but the idea is the same https://laravel.com/docs/5.7/blade#template-inheritance. Just instead of doing this:

views/layouts/app.blade.php

<html>
    <head>
        <title>App Name - @yield('title')</title>
    </head>
    <body>
        @section('sidebar')
            This is the master sidebar.
        @show

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

views/child.blade.php

@section('content')
    <p>This is my body content.</p>
@endsection

You should add the scripts tag to render the javascript. Like this:

views/layouts/app.blade.php

<html>
    <head>
        <title>App Name - @yield('title')</title>
    </head>
    <body>
        @section('sidebar')
            This is the master sidebar.
        @show

    
        @yield('scripts')
    </body>
</html>

views/child.blade.php

@section('scripts')
    <script>
        $( document ).ready(function() {
            console.log( "document loaded" );
        });
    </script>
@endsection
Vilfago's avatar

You have two questions, one in the title of the thread, and one in your message.

Most of us read the message and forget the title :)

I put all files in a js folder in asset, and use viewComposer to load only what I need in the layout.blade.php This way I load only the plugin I need, for the ones I don't often use.

martinbean's avatar

@catalin560 As @Vilfago says, you’re asking two questions: how to organise assets, and then conditionally loading assets.

In terms of organisation assets, just how Laravel starts me off: Vue components in the resources/js/components directory, and then pull them into my resources/js/app.js file, but “chunking” my components and conditionally loading them as per the Webpack docs page I linked above.

kobear's avatar

For organizing, I generally leave standalone scripts in assets/js. If it is a library that I download and upgrade, I put those in subfolders with a symbolic link to the library I am using.

For conditionally including code, I use @stack("scripts"). Stack allows you to include code from all the templates you are using.

Please or to participate in this conversation.