zoukankan      html  css  js  c++  java
  • ASP.NET MVC 在MVC 3项目中使用ASP.NET Bundling and Minification机制

    System.Web.Optimization是在ASP.NET 4.5中正式引入的。

    1. 在MVC 3中如何使用Bundling and Minification机制

    个人建议的方法,是在VS中建一个MVC 4的项目,看看Global.asax.cs里多了什么,看看App_Start目录下多了什么。

    MvcApplication.Application_Start() in Global.ascx.cs

    BundleTable.EnableOptimizations = `true`;  
    `BundleConfig.RegisterBundles`(BundleTable.Bundles);
    

    [内容已过期] http://joeyiodice.com/using-mvc4-minification-and-bundling-in-mvc3
    http://forums.asp.net/t/1799992.aspx/1
    在MVC 4中使用的官方教程

    2. 重要特性总结(待补充)

    1. Bundle使用了OutputCache
    2. 对物理文件修改后,文件变化可以立刻输出。原理是使用了缓存依赖,源文件作为依赖项。
    3. 文件内容相同的请求,v参数的值不变,因此可能会使用上浏览器内的客户端缓存。
    4. Bundle不能定义对不同domain的文件的引用。能否定义同域的但路径为虚拟路径的文件的引用,未知。

    3. 动态Bundle

    BundleApplication_Start时被注册到BundleTable.Bundles中。这样做的好处是,(预定义的)Bundle可以被重用。

    但如果仅有这一条途径注册Bundle,有时候会觉得未免太繁琐:

    1)修改BundelConfig.cs

    2)重新编译项目

    3)忍受站点启动缓慢的过程。

    假如你遇到的情形是,某个页面上需要一个偶尔使用的一个或多个js,你想利用**Bundling and Minification机制**对其打包或启用压缩,有没有简单点的办法呢?

    看下别人的解决方案:

    前面的问题很好的解决了。现在试着想一个新问题,这样做是否就无法满足**重用Bundle**的需求呢?如果你了解MVC 2,可以试着用MVC 2中引入的DisplayTemplates机制解决这个问题。

    4. Sample

    静态Bundle

    // 注册
    public static void RegisterBundles(BundleCollection bundles)
    {
        var styleBundle = new StyleBundle("~/Content/css").Include(
            "~/css/reset.css",
            "~/css/common.css",
            "~/css/layout.css"
        );
        bundles.Add(styleBundle);
    }
    
    @*使用*@
    @Styles.Render("~/Content/css")
    

    动态Bundle

    // 定义
    public static IHtmlString DynamicScriptsBundle(this HtmlHelper htmlHelper, string nombre, params string[] urls)
    {
        string path = string.Format("{0}", nombre);
        if (BundleTable.Bundles.GetBundleFor(path) == null)
            BundleTable.Bundles.Add(new ScriptBundle(path).Include(urls));
        return Scripts.Render(path);
    }
    

    asp-net-mvc-4-use-bundles-beneficts-for-url-content
    runtime-bundling-and-minifying-in-mvc-4

    @*使用*@
    @Html.DynamicScriptsBundle("~/Scripts/Common", "~/js/common.js")
    

    延伸阅读

    a-localized-scriptbundle-solution

    yicone
    -The future is worth fighting for.
  • 相关阅读:
    响应式设计工作总结
    首页性能指标
    前端工作小结
    html5、css3小应用
    循环滚动实例
    程序员修炼之道笔记(转)
    一个操作系统的实现(1)
    scrum role
    一个操作系统的实现(3)
    awk&sed story
  • 原文地址:https://www.cnblogs.com/yicone/p/2801579.html
Copyright © 2011-2022 走看看