Search code examples
laravellaravel-bladelaravel-9

Laravel - Prevent duplicate script tags when using partials/modals


I have a few update forms that exist on multiple pages. To reduce workload, I have built these forms as partials/modals that can be @included when needed. Some of the forms utilize a mask.js so I also include an @parent for 'scripts' to include the tag.

It works, but I think I may be attempting to load external JS multiple times if two of the forms use the mask.js and are included in the same view blade.

For example:

Main Page

@include('partials.newdate')
@include('partials.olddate')

partials/newdate.blade.php

@section('scripts')
@parent
<script src="/js/jquery.mask.min.js"></script>
@stop

partials/olddate.blade.php

@section('scripts')
@parent
<script src="/js/jquery.mask.min.js"></script>
@stop

both of the partials need this script, but I also would like to avoid loading it on all pages to reduce load times.

Is there something I can do to "check" for jquery.mask.min.js before laravel adds it to the script section?


Solution

  • You could use the once directive

    https://laravel.com/docs/9.x/blade#the-once-directive

    @once
        @push('scripts')
            <script>
                // Your custom JavaScript...
            </script>
        @endpush
    @endonce