Tuesday, May 31, 2011

Combining Css and javascript into one http request in ASP.NET 2.0.

We always include many javascript and css file into our page.aspx file,


here is code that combined all javascript into one javascript and all CSS into one CSS  using a handler.
here is steps for doing so....


make a handler named HttpCombiner.ashx into your root directory.


//HttpCombiner.ashx



<%@ WebHandler Language="C#" Class="HttpCombiner" %>


using System;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Configuration;
using System.Web;


public class HttpCombiner : IHttpHandler {
    
    public void ProcessRequest(HttpContext context)
        {
        // Get the list of CSS files from QueryString.
        string files = context.Request.QueryString["fileName"];
        if (string.IsNullOrEmpty(files))
            {
                return; // If no file name is mentioned then don't proceed.
            }


        // Get the list of files specified in the querystring (joined by ',').
        string[] arrFileNames = files.Split(',');
        if ((arrFileNames != null) && (arrFileNames.Length > 0))
            {
            string filePath = string.Empty;


            // Read the content of each CSS file and write it in the response.
            for (int fileCount = 0; fileCount < arrFileNames.Length; fileCount++)
                {
                filePath = context.Server.MapPath(arrFileNames[fileCount]).Trim();
                if (File.Exists(filePath)) // Check if the file exists in the physical location or not.
                    {
                        context.Response.Write(File.ReadAllText(filePath));
                    }
                }
            //context.Response.ContentType = "text/css"; // Set the content type.
            }
        }


    public bool IsReusable
    {
        get
        {
            return true;
        }
    }


}


Add the following code into your .cs file for CSS...



HtmlLink htmllnkcss = new HtmlLink();
        htmllnkcss.Href = "HttpCombiner.ashx?fileName=themes/css/abc.css,themes/css/xyz.css";
        htmllnkcss.Attributes.Add("rel", "stylesheet");
        htmllnkcss.Attributes.Add("type", "text/css");       
        hdflight.Controls.Add(htmllnkcss);


and for javascript...



HtmlGenericControl javascript = new HtmlGenericControl("script");
        javascript.Attributes["src"] = "HttpCombiner.ashx?fileName=js/jquery-1.3.2.min.js,js/blockui.js";
        javascript.Attributes["type"] = "text/javascript";
        hdflight.Controls.Add(javascript);


and now run your page and enjoy.....


No comments:

Post a Comment