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

Ligonsker's avatar

Why does it say in the Vite docs to place the JS scripts inside the head tags?

Hello,

Looking at the Vite docs: https://laravel.com/docs/10.x/vite#loading-your-scripts-and-styles

It says to place the Vite JS scripts inside the <head> tags together with the CSS:

<!doctype html>
<head>
    {{-- ... --}}
 
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>

But why? Shouldn't I place the JS scripts at the bottom of the tags? Or Vite takes care of that by maybe deferring their load?

Ty

0 likes
9 replies
jlrdw's avatar

That's usually where css and js is loaded, between head tags.

2 likes
Ligonsker's avatar

@jlrdw Shouldn't JS be at the bottom of <body>? Really curious because all I remember is that it's better for it to be at the bottom because of loading times. But maybe that's different nowadays?

1 like
jlrdw's avatar

@Ligonsker code used on a page yes at bottom the library is loaded in the head.

1 like
Ligonsker's avatar

@jlrdw Got it, thanks! Do you know if it uses defer by default or I should somehow add it myself? Or maybe add:

document.addEventListener("DOMContentLoaded", function() {

});

to my JS files?

Snapey's avatar

Code is typically last to avoid blocking the page load, so I guess it must be using defer.

I'm guessing because TBH I avoid building any JS

1 like
Ligonsker's avatar

@Snapey So you just place the JS files you need per page at the bottom of the <body>?

Snapey's avatar

@Ligonsker yes. Old school. It works and its efficient. However I'm not using a front end javascript stack.

1 like
Ligonsker's avatar

@Snapey Me neither, I just thought that packages like Vite (or Mix) help reduce the size of the files, but maybe when using per-page scripts it's really unnecessary. (I currently doing it to learn Vite in general so I might also just do CSS)

Please or to participate in this conversation.