MVC 4 - 在何处加载JS脚本 [英] MVC 4 - Where to load JS Scripts

查看:138
本文介绍了MVC 4 - 在何处加载JS脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当新的MVC和我注意到有很多不一致的与我已经写了加载JS文件,并试图加载。

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)

我使我的MainMenu在布局的身体。所有的jQuery脚本在布局的页脚装(我读的地方,是preferrable)。

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.

什么是去加载JavaScript文件(从谷歌或文件包含在我的项目无论是CDN文件)的最好方法?我应该载入所有的人都在我的布局页的标题,或者只是加载它们,因为我使用它们?有人能说明一下最佳实践和管理/负载/使用MVC应用程序的JavaScript文件。

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.

感谢您的输入!

推荐答案

如果您使用的是 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.

这篇关于MVC 4 - 在何处加载JS脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆