MVC 4 - Where to Load JS Scripts

I am new to MVC and I noticed a lot of inconsistencies when loading js files that I wrote and tried to load.

To get started, this is how I set up my site:

    _Layout.cshtml (main page)
Index.cshtml
_MainMenu.cshtml (partial view)

      

I am doing my MainMenu in the body of the layout. All jquery scripts are loaded in the layout footer (I read somewhere which was preferred).

When I create a view, I load any specific scripts associated with that content at the top of the view.

What is the best way to load javascript files (be they cdn files from google or files included in my project)? Should I load them all in the header of my layout page, or should I just load them when I use them? Can someone explain the best practice and managing / loading / using javascript files in mvc app.

Thanks for your input!

+3


source to share


1 answer


If you are using Modernizr , load this into your head. Download other scripts including jquery at the bottom body

(unless otherwise noted - some scripts require head

). Ideally, your _Layout.cshtml would look like this:

<!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>

      

This way you load your jQuery package and then a section where you can load your own scripts into the page if needed, like (in another file .cshtml

):

@section Scripts {
    @Scripts.Render("~/bundles/myNiceBundle")
}

      



so it will put your custom scripts in jQuery.

Mandatory reason for placing scripts at the bottom of the page :

The problem caused by scripts is that they block parallel downloads. The HTTP / 1.1 specification assumes that browsers no longer download more than two components in parallel for a hostname. If you serve your images from multiple hostnames, you may get more than two uploads in parallel. However, when loading the script, the browser won't run any other downloads, even on different hostnames.

+10


source







All Articles