Reputation: 520
I am fairly new to MVC and I have noticed a lot of inconsistencies with loading js files I have written and tried to load.
To start, here is how I have my website setup:
_Layout.cshtml (main page)
Index.cshtml
_MainMenu.cshtml (partial view)
I render my MainMenu in the body of Layout. All jquery scripts are loaded in the footer of layout (I read somewhere that was preferrable).
When I render a view, I load any specific scripts related to that content at the top of the view.
What is the best way to go about loading javascript files (whether it's cdn files from google or files included in my project)? Should I load all of them in the header of my layout page, or just load them as I use them? Can someone please explain the best practice and managing/loading/using javascript files in an mvc application.
Thank you for your input!
Upvotes: 3
Views: 9189
Reputation: 15797
If you are using Modernizr, load that in the head. Load your other scripts, including jquery, in the bottom of the body
(unless specified otherwise -- some scripts will require to be head
). Ideally, your _Layout.cshtml would look like:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- head stuff -->
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<!-- your entire body -->
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
So that will load your jQuery bundle, and then a section where you can load custom scripts per page, as needed, like (in some other .cshtml
file):
@section Scripts {
@Scripts.Render("~/bundles/myNiceBundle")
}
so it will put your custom scripts under jQuery.
Obligatory reason for putting scripts at bottom of page:
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.
Upvotes: 10