views:

18

answers:

2

Hi all,

Could anyone please tell me about how one might go about implementing your own custom tags in JS pages served by ASP.NET?

Basically what I am looking to achieve is a way of creating "includes" for my Javascript files by adding some code such as.

//Include Src="MyJavascriptFileLocation.JS"

And then having the ASP.Net handler serve my javascript file but also dynamically append the referenced javascript file to the location where the include is written.

Could anyone please guide me in the direction I need to go to accomplish this?

+1  A: 

You could do this by including the name of the Javascript file in an HTML comment and then overloading the Render method of the System.Web.UI.Page object to search for these comments and replace them with the text from the JavaScript files.

In your markup:

<!-- Include Src="MyJavascriptFileLocation.JS" -->

In your C# code:

        protected override void Render(System.Web.UI.HtmlTextWriter writer)

        {

            // First, grab the HTML that would have been sent

            System.IO.StringWriter stringWriter = new System.IO.StringWriter();

            HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);

            base.Render(htmlWriter);

            string html = stringWriter.ToString();



            // Look for comment
            int start = html.IndexOf("<!-- Include");



            // If found...

            if (start >= 0)

            {

                             // Code here to replace comment with JavaScript file
            }

            // Output our refactored HTML

            writer.Write(html);
       }

If you want more than one JavaScript file per page then you could use a while loop and repeat the search and replace until you find them all.

I am not sure this is the best thing to do. Dynamically adding in the JavaScript would really mess with the caching and such. You do minimize the number of requests the client needs to make though.

I will leave it to you if what you are asking for makes sense and just answer the question. You know a lot more about what you are trying to achieve than I do.

Justin
A: 

I just realized that you may actually be asking how to inlcude a JavaScript file into another JavaScript file. In this case, your question is not really .NET specific since the JavaScript is parsed and executed on the client (in the browser).

If this is what you want, here is a link that talks about it:

http://www.cryer.co.uk/resources/javascript/script17_include_js_from_js.htm

Justin