{ independency injection }

One of the best-practices recommendations I have struggled with is to have all your <script> tags at the bottom of the page. This is easily accomplished from a standard view; Create a section in your layout called "scripts" that renders just below where you load the libraries and use this section wherever you need scripting. No problem.

Notice I said, "standard view"? What happens if you have a partial that requires some script to run? Some would argue that the scripts should not be in the partial, but I have had a few special cases where this simply isn't possible.

I have a common "Message" partial, who's job is to render messages to the page. Most of these messages are HTML and display normally, but some messages are actually "growl" type notification messages and the partial needs to execute a function on rendering. HERE is the problem. You can't write to a section from a partial, plus partials are sometimes rendered via AJAX.

I needed a way to get the script block from my partial rendered after the scripts are loaded if part of an entire view, but I want to load the scripts inline, should I render the partial using AJAX (since the libraries will be loaded already at this point).

Sure, I could use a Head.js or some other script loading library, but some of these break the "unobtrusive" libraries that come with MVC and I didn't want to lose that functionality.

Templated Delegates to the Rescue

I created a ScriptBlock extension-method that accepts a templated delegate from anywhere in a view. The extensions method determines if the request is AJAX or not and writes the script back to the view if it is. If the partial is part of an entire view page, the script is captured in a StringBuilder, stored in HttpContext. A counterpart extension method "WriteScriptBlocks" can then be included in my layout, wherever I want the scripts to render.

Check it out.

Extention Methods:

Using the templated delegate as a parameter is great, because any model-view-binding is executed before the content is delivered to this function. Since it's a template, Intellisense and code coloring also works. Here it is, in use: