Bundling and Minification
what will happen, if I boundle a js file with Bundle and manually reference the same file again on html
If you bundle a JS file with Bundle and manually reference the same file again on HTML, the following will happen:
- The browser will download both the bundled JS file and the unbundled JS file.
- The browser will execute the unbundled JS file first, and then the bundled JS file.
- If there are any conflicts between the two versions of the JS file, the unbundled JS file will take precedence.
In general, it is not recommended to manually reference a JS file that has already been bundled. This can lead to performance problems and conflicts between the two versions of the file.
ScriptBundle vs Bundle vs StyleBundle in asp.net
ScriptBundle and StyleBundle are specialized versions of the Bundle class in ASP.NET. They are used to bundle JavaScript and CSS files, respectively. The main difference between a Bundle and a ScriptBundle or StyleBundle is that the latter two classes automatically minify the bundled files. This can improve the performance of your web application by reducing the size of the JavaScript and CSS files that are downloaded by the browser.
Another difference between Bundle and ScriptBundle or StyleBundle is that the latter two classes provide additional features for working with JavaScript and CSS files. For example, ScriptBundle allows you to order the scripts in the bundle and specify dependencies between them. StyleBundle allows you to merge CSS files and specify media types for each file.
Here is a table that summarizes the key differences between ScriptBundle, Bundle, and StyleBundle:
Feature | ScriptBundle | Bundle | StyleBundle |
---|---|---|---|
Minifies bundled files | Yes | No | Yes |
Orders scripts in bundle | Yes | No | No |
Specifies dependencies between scripts | Yes | No | No |
Merges CSS files | No | No | Yes |
Specifies media types for CSS files | No | No | Yes |
When to use ScriptBundle, Bundle, or StyleBundle:
- Use ScriptBundle if you need to bundle JavaScript files and minify them.
- Use Bundle if you need to bundle JavaScript or CSS files, but you do not need to minify them.
- Use StyleBundle if you need to bundle CSS files, merge them, and specify media types for each file.
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:
Original | Renamed |
---|---|
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.
Using B/M | Without B/M | Change | |
---|---|---|---|
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 (Scripts\jquery-ui-1.8.11.min.js and Scripts\jquery-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:
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
- For Web Pages, see the blog entry Adding Web Optimization to a Web Pages Site.
- For Web Forms, see the blog entry Adding Bundling and Minification to Web Forms.
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\_Start\BundleConfig.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>
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2016-03-31 DockPanel的使用