Dynamically create .js (or .css) file

by Miro 6. August 2008 05:59

For one of my project I needed a dynamically created JavaScript file. This file contains a class which has all messaged used by the client-side javascript.

1. Create a HttpHandler 

    public class MyMessageHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            HttpResponse response = HttpContext.Current.Response;

            try
            {
                response.AddHeader("Content-Type", "text/javascript");
                //dynamically create file contents string, use the StringBuider, etc...
                response.Write("function x() {alert('doing something');}") 
            }
            catch (Exception ex)
            {
                //handle the exception if necessary
            }
            finally
            {
                response.End();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

2. Set up the web.config file

<httpHandlers>
     //other handlers
      <add verb="*" path="*/scripts/messages.js" validate="false" type="MyClass.MyMessageHandler, MyClass" />
</httpHandlers> 

the path can be anything as long as it's properly referenced from the page

3. Reference the path as it was pointing to a physical JavaScript file

 <script type="text/javascript" src="/scripts/messages.js"></script> 

Done. 

Tags:

.NET | JavaScript

Powered by BlogEngine.NET
Contents copyright 2008 Mirocle Pty. Ltd. All Rights Reserved.