Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

splaq's avatar

Best way to load javascript on a per page basis?

Basically I'm looking for a way to use a bit on javascript on one page while not on another.. This way (at least in a large scale application) you will be saving load times and bandwidth if you're not loading all of the site's javascript on the master template..

I would imagine you could include it in the templates but that wouldn't be semantically correct would it? Also what's the point of having a long @if/@elseif statement in your blade? Kind of seems like overkill to me.

Maybe including a variable in your route/controller that holds the link tag to the script you want to run and pass that through to the view with the rest of your data? That almost seems like the best way to do it or does it? What are your thoughts?

I may be putting this into practice but right now javascript in the application I'm working on is just a thought.. I may just keep it simple. But in principle this is a question and thought on best practices I suppose.

What are your theories and why?

0 likes
8 replies
jlrdw's avatar

You can include it on the page you need it.

jimmck's avatar

@splaq Hi. If you are using Blade, just @include and then include .js files or code. Or more HTML and code and/or files. I mix Vue components in this way.

milon's avatar

use webpack as your component manager

Snapey's avatar

In your master layout include a line @yield('pagescript')

Then in the blade file for the view that needs the javascript, include a section that pulls in required javascript for that view. Views that do not have a 'pagescript' section will not throw errors.

@section('pagescript')
    <script src="/js/jquery.transit.min.js"></script>
@stop
9 likes
notflip's avatar

@milon How would you do that using Webpack? Can't imagine you can split it off per page?

1 like
saidbakr's avatar

"use webpack as your component manager"

@milon How could I do that from the view?

simplenotezy's avatar

And what if you're using Require? E.g. in your app.js do:

 var Login = require('./Login');

And then on login.blade.php, you would like to do something with the Login variable.

E.g.:

<script>
    window.deferAfterjQueryLoaded.push(function() { 
        $(function() {
            Login.initialize({

            });
        });
    });
</script>

Then it would complain that Login is not defined.

Please or to participate in this conversation.