且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MVC 4 - 在何处加载JS脚本

更新时间:2023-12-05 15:40:40

如果您使用的是 Modernizr的,加载在目。装入其它脚本,包括jQuery的,在(底部,除非另有规定 - 一些脚本将要求为)。理想情况下,你的_Layout.cshtml看起来像:

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>

这样会加载jQuery的包,然后一个部分,在那里你可以加载自定义脚本每页,根据需要,像(在一些其他的 .cshtml 文件):

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

所以它会把你的自定义脚本的jQuery之下。

so it will put your custom scripts under jQuery.

强制性理由把脚本在页面的底部:

引起的脚本的问题是,它们阻止并行下载。
  在HTTP / 1.1规范建议浏览器下载没有更多
  比在每个主机并行两种组分。如果你为你的图片
  从多个主机名,你可以得到出现两个以上的下载
  在平行下。虽然脚本下载,然而,浏览器将不会
  启动任何其他下载,甚至在不同的主机名。

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.