Install
necessary Dlls using Package Manager console.
PM> Install-Package
Microsoft.AspNet.Web.Optimization
Now add a class file and copy below code in it :
using System.Web.Optimization;
public class Bundle
{
public void AddBundle()
{
var JSBundle = new ScriptBundle("~/JSfiles");
JSBundle.Include("~/Scripts/jquery-1.7.1.js");
JSBundle.Include("~/Scripts/jquery-1.7.1.min.js");
// JSBundle.Include("~/ Path of your file with ext.");
BundleTable.Bundles.Add(JSBundle);
var styleBundle = new StyleBundle("~/Style");
styleBundle.Include("~/Styles/Site.css");
// styleBundle.Include("~/ Path of your file with ext.");
BundleTable.Bundles.Add(styleBundle);
}
}
Register your bundle in Application_Start event in Global.asax :
protected void Application_Start(object sender,
EventArgs e)
{
Bundle bndle =
new Bundle();
bndle.AddBundle();
}
Now Take .aspx page in which you want to render your bundled css or JS files.
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<%: System.Web.Optimization.Scripts.Render("~/JSfiles") %>
<%: System.Web.Optimization.Styles.Render("~/Style") %>
<script>
$(document).ready(function () {
alert("done");
})
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Now in Web.config. If you want to enable bundling for your application then you have to make debug = false.
<system.web>
<compilation debug="false" targetFramework="4.5"/>
</system.web>
Now check if your bundling is working or Not ?
Press F12 in IE. Then Script Tab and check in drop-down in right side. You will have name of the JS file which you have given in application. if you click on that you will find minified JS of all JS. You will not found actual path of your JS. see Page Source
Enjoy................
No comments:
Post a Comment