It use to be that you would have to summon the mighty powers of YUI compressor and roll out the red carpets of MSBuild to minify CSS and JS files in your ASP.NET and MVC applications. With the introduction of bundling in System.Web.Optimization (now Microsoft.AspNet.Web.Optimization) you can skip the formalities and bundle your JS and CSS file without introducing additional dependencies.
To use bundling in a .NET 4.0 app.
1- Create an App_Start folder in your solution (if you don't have one already)
2- Add a class in your App_Start folder for your bundles and create a function to call all your CSS and JS files.
E.g. (BundleConfig.cs)
3- Add reference to the optimization classes and register your bundles on Application_Start() event in Global.asax.
First
Then
4- Call your bundles on any page with Styles.Render or Scripts.Render function on your .aspx or .cshtml (for razor) pages.
E.g.
@Styles.Render("~/styles/style") // for CSS
@Scripts.Render("~/scripts/script") // for JS
After adding the render function to your page you will have all your JS and CSS files on your page every time your page loads. To see your little .NET bundle of joy full with minified JS and CSS just change your compilation settings from debug = "true" to "false" in web.config.
To use bundling in a .NET 4.0 app.
1- Create an App_Start folder in your solution (if you don't have one already)
2- Add a class in your App_Start folder for your bundles and create a function to call all your CSS and JS files.
E.g. (BundleConfig.cs)
Code Snippet
- using System.Web;
- using System.Web.Optimization;
- namespace YourGlobalNameSpace
- {
- public class BundleConfig
- {
- public static void RegisterBundles(BundleCollection bundles)
- {
- bundles.Add(new StyleBundle("~/styles/style").Include
- ("~/style/style1.css"));
- bundles.Add(new ScriptBundle("~/scripts/script").Include
- (("~/scripts/script1.js"));
- }
- }
- }
3- Add reference to the optimization classes and register your bundles on Application_Start() event in Global.asax.
First
Code Snippet
- using System.Web.Optimization;
Then
Code Snippet
- protected void Application_Start()
- {
- YourGlobalNameSpace.RegisterBundles(BundleTable.Bundles);
- }
4- Call your bundles on any page with Styles.Render or Scripts.Render function on your .aspx or .cshtml (for razor) pages.
E.g.
@Styles.Render("~/styles/style") // for CSS
@Scripts.Render("~/scripts/script") // for JS
After adding the render function to your page you will have all your JS and CSS files on your page every time your page loads. To see your little .NET bundle of joy full with minified JS and CSS just change your compilation settings from debug = "true" to "false" in web.config.
Comments