Updated 8/29/2018 - Formatted
In ASP.Net 4.5 there is a new feature called "Bundling". Now you might ask whad does it do?. Bundling bundles multiple files into a single file. For example if you want to use two CSS and five jQuery files in your page and all are in the styles and scripts folder. What you will do? , you provide the path for all CSS and jqery file in your page like:
For CSS file:
- <link href='<%= ResolveUrl("~/Styles/Test1.css")%>' rel="stylesheet" type="text/css" />
- <link href='<%= ResolveUrl("~/Styles/Test2.css")%>' rel="stylesheet" type="text/css" />
For jQuery file:
- <script src='<%= ResolveUrl("~/Scripts/Test1.js")%>' type="text/javascript"></script>
- <script src='<%= ResolveUrl("~/Scripts/Test2.js")%>' type="text/javascript"></script>
- <script src='<%= ResolveUrl("~/Scripts/Test3.js")%>' type="text/javascript"></script>
- <script src='<%= ResolveUrl("~/Scripts/Test4.js")%>' type="text/javascript"></script>
- <script src='<%= ResolveUrl("~/Scripts/Test5.js")%>' type="text/javascript"></script>
Now when you load your page then seven requests will go to the server. Bundling will reduce the number of requests sent to the server. You can do this easly in 4.5.
In this article I will tell you how to use Bundling in ASP.Net 4.0.
By the preceding description about Bundling you can easily understand that Bundling is used for performance optimization.
To use the Bundling feature in ASP.Net 4.0 you will need the following two DLLs:
- System.Web.Optimization.dll
- WebGrease.dll
Now add references for both DLLs in your web
.
In the following sample code I am using two CSS files in the content folder so both files are bundled for the single request.
Now add the following line of code in the Application_Start event of global.asax to register the bundle.
- RegisterBundles(System.Web.Optimization.BundleTable.Bundles);
- BundleTable.EnableOptimizations = true;
Now in web.config add the following line to give the reference of the added DLL in your web.config file.
- <system.web>
- <compilation debug="true" targetFramework="4.0" />
- <pages>
- <namespaces>
- <add namespace="System.Web.Optimization" />
- </namespaces>
- <controls>
- <add assembly ="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
- </controls>
- </pages>
- </system.web>
Now add the following line given below in your masterpage head section.
- <%: System.Web.Optimization.Styles.Render("~/Content/css") %>
Now you can check on your page, it bundles both files in "css?v=".
And you can see only two requests went to server one for the aspx page and another for the CSS.