views:

140

answers:

1

I have a page that is referenced via a <script> tag from a page on another site. In the script src, I pass in the form I want my script to build (from a db table), and the div where the dynamically built form should go. The calling page looks something like this:

<div id="FormContainer"></div>
<script type="text/JavaScript" src="http://www.example.com/GenerateForm.aspx?FormId=1&amp;div=FormContainer"&gt;&lt;/script&gt;

GenerateForm.aspx contains the code that reads the QueryString parameters for the FormId, and the Div Id, and outputs JavaScript that will build the form.

My question is this. What are the different methods for "outputting" the JavaScript? Some of the JavaScript is static, and can be packaged into an external .js file and I have jQuery too. But should I add that on the GenerateForm.aspx markup page? Or should I use a ScriptManager?

And what about the dynamically built JavaScript? Currently I'm just using Response.Write() for a proof of concept, but instead, should I be doing something else? Use a Literal control on the page and set its value? Use a ScriptManager? Something else?

I know this is a verbose question, so thanks in advance!

+2  A: 

If you want to use a seperate, referenced Javascript file, you probably want to do is use an ashx file. Basically this is just a generic handler that you'll use to write directly to the output stream without having to deal with the ASP.NET page lifecycle. If you add a basic Generic Handler (.ashx) to your site from the Add New Item dialog, the template should be enough direction, using context.Response.Write() to output your Javascript dynamically.

The ScriptManager is more useful if you want to output individual lines of Javascript to be ran at certain times, like after an event has fired. Then you can do ScriptManager.RegisterClientBlock(this, this.GetType(), "CodeBlock", "alert('Button clicked');", true); to show a client alert box after a button has been clicked, for example.

Static files should be handled just that way - statically. The server can handle the caching, and does not cause unnecessary processing if you reference the static script file directly from the script tag. However, if you need to load a static script dynamically, you could, for example, create a literal that had the <script> tag inside it. This way it uses the browser's cached version of the static file.

Andrew Koester