在 ASP.NET MVC 中组合和缩小 JS 和 CSS

2024-02-03

我创建了默认的 ASP.NET MVC 3 Web 应用程序。然后我将三个 css 和三个 js 文件添加到 \Views\Shared_Layout.cshtml 视图中:

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/StyleSheet1.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/StyleSheet2.css")" rel="stylesheet" type="text/css" />

    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/JScript1.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/JScript2.js")" type="text/javascript"></script>

</head>
<body>
    <div class="page">
        <div id="header">

....

当我运行应用程序时,我的 html 代码是

<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>
    <link href="/Content/Site.css" rel="stylesheet" type="text/css" />
    <link href="/Content/StyleSheet1.css" rel="stylesheet" type="text/css" />
    <link href="/Content/StyleSheet2.css" rel="stylesheet" type="text/css" />

    <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script src="/Scripts/JScript1.js" type="text/javascript"></script>
    <script src="/Scripts/JScript2.js" type="text/javascript"></script>

</head>
<body>
    <div class="page">

是否可以在 MVC 中有一个处理程序来将我的输出 html 更改为:

<!DOCTYPE html>
    <html>
    <head>
        <title>Home Page</title>
        <script src="js.axd=/Scripts/jquery-1.5.1.min.js,/Scripts/JScript1.js,/Scripts/JScript2.js" type="text/javascript"></script>
        <link href="css.axd=/Content/Site.css,/Content/StyleSheet1.css,/Content/StyleSheet2.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <div class="page">

所以链接js.axd=/Scripts/jquery-1.5.1.min.js,/Scripts/JScript1.js,/Scripts/JScript2.js会将所有这些js文件的内容返回给浏览器,并链接css.axd=/Content/Site.css,/Content/StyleSheet1.css,/Content/StyleSheet2.css将返回所有 css 文件的内容。

我之前在 ASP.NET 中通过 IHttpHandler 做过一些事情,但不知道如何在 MVC 中做到这一点,因为我只是 MVC 的初学者。

任何帮助和代码示例将不胜感激。 谢谢你!


您可以使用捆绑包和缩小 nuget 包。捆绑和缩小 http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification

At the NuGet console type: "Install-Package Microsoft.AspNet.Web.Optimization"

这里的例子:

将 Web 优化与 MVC 3 结合使用 http://icanmakethiswork.blogspot.co.uk/2012/10/using-web-optimization-with-mvc-3.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 ASP.NET MVC 中组合和缩小 JS 和 CSS 的相关文章