zoukankan      html  css  js  c++  java
  • Bundling and Minification

    Bundling and Minification

    Most of the current major browsers limit the number of simultaneous connections per each hostname to six. That means that while six requests are being processed, additional requests for assets on a host will be queued by the browser. In the image below, the IE F12 developer tools network tabs shows the timing for assets required by the About view of a sample application.

    Bundling

    Bundling is a new feature in ASP.NET 4.5 that makes it easy to combine or bundle multiple files into a single file. You can create CSS, JavaScript and other bundles. Fewer files means fewer HTTP requests and that can improve first page load performance.

    The following image shows the same timing view of the About view shown previously, but this time with bundling and minification enabled.

    Minification

    Minification performs a variety of different code optimizations to scripts or css, such as removing unnecessary white space and comments and shortening variable names to one character. Consider the following JavaScript function.

    AddAltToImg = function (imageTagAndImageID, imageContext) {
        ///<signature>
        ///<summary> Adds an alt tab to the image
        // </summary>
        //<param name="imgElement" type="String">The image selector.</param>
        //<param name="ContextForImage" type="String">The image context.</param>
        ///</signature>
        var imageElement = $(imageTagAndImageID, imageContext);
        imageElement.attr('alt', imageElement.attr('id').replace(/ID/, ''));
    }

    After minification, the function is reduced to the following:

    AddAltToImg = function (n, t) { var i = $(n, t); i.attr("alt", i.attr("id").replace(/ID/, "")) }

    n addition to removing the comments and unnecessary whitespace, the following parameters and variable names were renamed (shortened) as follows:

    Table 1
    OriginalRenamed
    imageTagAndImageID n
    imageContext t
    imageElement i

    Impact of Bundling and Minification

    The following table shows several important differences between listing all the assets individually and using bundling and minification (B/M) in the sample program.

    Table 2
     Using B/MWithout B/MChange
    File Requests 9 34 256%
    KB Sent 3.26 11.92 266%
    KB Received 388.51 530 36%
    Load Time 510 MS 780 MS 53%

    The bytes sent had a significant reduction with bundling as browsers are fairly verbose with the HTTP headers they apply on requests. The received bytes reduction is not as large because the largest files (Scriptsjquery-ui-1.8.11.min.js and Scriptsjquery-1.7.1.min.js) are already minified. Note: The timings on the sample program used the Fiddler tool to simulate a slow network. (From the Fiddler Rules menu, select Performance then Simulate Modem Speeds.)

    Debugging Bundled and Minified JavaScript

    It's easy to debug your JavaScript in a development environment (where the compilation Element in the Web.config file is set to debug="true" ) because the JavaScript files are not bundled or minified. You can also debug a release build where your JavaScript files are bundled and minified. Using the IE F12 developer tools, you debug a JavaScript function included in a minified bundle using the following approach:

    https://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/s10awwz0(v=vs.100)?redirectedfrom=MSDN

    debug 

    Optional Boolean attribute.

    Specifies whether to compile debug binaries rather than retail binaries.

    The default is False.

    Controlling Bundling and Minification

    Bundling and minification is enabled or disabled by setting the value of the debug attribute in the compilation Element in the Web.config file. In the following XML, debug is set to true so bundling and minification is disabled.

    <system.web>
        <compilation debug="true" />
        <!-- Lines removed for clarity. -->
    </system.web>

    To enable bundling and minification, set the debug value to "false". You can override the Web.config setting with the EnableOptimizations property on the BundleTable class. The following code enables bundling and minification and overrides any setting in the Web.config file.

    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                     "~/Scripts/jquery-{version}.js"));
    
        // Code removed for clarity.
        BundleTable.EnableOptimizations = true;
    }

    Unless EnableOptimizations is true or the debug attribute in the compilation Element in the Web.config file is set to false, files will not be bundled or minified. Additionally, the .min version of files will not be used, the full debug versions will be selected. EnableOptimizations overrides the debug attribute in the compilation Element in the Web.config file

    Using Bundling and Minification with ASP.NET Web Forms and Web Pages

    Using Bundling and Minification with ASP.NET MVC

    In this section we will create an ASP.NET MVC project to examine bundling and minification. First, create a new ASP.NET MVC internet project named MvcBM without changing any of the defaults.

    Open the App\_StartBundleConfig.cs file and examine the RegisterBundles method which is used to create, register and configure bundles. The following code shows a portion of the RegisterBundles method.

    public static void RegisterBundles(BundleCollection bundles)
    {
         bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                     "~/Scripts/jquery-{version}.js"));
             // Code removed for clarity.
    }

    The preceding前述的 code creates a new JavaScript bundle named ~/bundles/jquery that includes all the appropriate (that is debug or minified but not .vsdoc) files in the Scripts folder that match the wild card string "~/Scripts/jquery-{version}.js". For ASP.NET MVC 4, this means with a debug configuration, the file jquery-1.7.1.js will be added to the bundle. In a release configuration, jquery-1.7.1.min.js will be added. The bundling framework follows several common conventions such as:

    • Selecting ".min" file for release when FileX.min.js and FileX.js exist.
    • Selecting the non ".min" version for debug.
    • Ignoring "-vsdoc" files (such as jquery-1.7.1-vsdoc.js), which are used only by IntelliSense.

    The {version} wild card matching shown above is used to automatically create a jQuery bundle with the appropriate version of jQuery in your Scripts folder. In this example, using a wild card provides the following benefits:

    • Allows you to use NuGet to update to a newer jQuery version without changing the preceding bundling code or jQuery references in your view pages.
    • Automatically selects the full version for debug configurations and the ".min" version for release builds.

    Using a CDN

    The follow code replaces the local jQuery bundle with a CDN jQuery bundle.

    public static void RegisterBundles(BundleCollection bundles)
    {
        //bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
        //            "~/Scripts/jquery-{version}.js"));
    
        bundles.UseCdn = true;   //enable CDN support
    
        //add link to jquery on the CDN
        var jqueryCdnPath = "https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js";
    
        bundles.Add(new ScriptBundle("~/bundles/jquery",
                    jqueryCdnPath).Include(
                    "~/Scripts/jquery-{version}.js"));
    
        // Code removed for clarity.
    }

    In the code above, jQuery will be requested from the CDN while in release mode and the debug version of jQuery will be fetched locally in debug mode. When using a CDN, you should have a fallback mechanism in case the CDN request fails. The following markup fragment from the end of the layout file shows script added to request jQuery should the CDN fail.

    </footer>
    
            @Scripts.Render("~/bundles/jquery")
    
            <script type="text/javascript">
                if (typeof jQuery == 'undefined') {
                    var e = document.createElement('script');
                    e.src = '@Url.Content("~/Scripts/jquery-1.7.1.js")';
                    e.type = 'text/javascript';
                    document.getElementsByTagName("head")[0].appendChild(e);
    
                }
            </script> 
    
            @RenderSection("scripts", required: false)
        </body>
    </html>
  • 相关阅读:
    如何修改dmesg log buffer size
    phpmyadmin的初始账号密码是多少
    DirectFB 之 FillRectangle 绘制矩形
    DFB系列 之 Clear清空surface缓存
    DFB系列 之 Flip()更新buffe
    DFB系列 之 Bilp叠加
    DFB系列 之 SetCooperativeLevel协作级别
    DirectFB 之 实例图像不断右移
    DirectFB 之 环境配置
    DirectFB 之 简介
  • 原文地址:https://www.cnblogs.com/chucklu/p/12604666.html
Copyright © 2011-2022 走看看