This is a bit hacky, but if your goal is to affect minimal changes on existing views (besides moving the rendered scripts), the way I've done it in the past (in Web Forms specifically but would also apply to MVC) was to override the TextWriter
with one that pushes scripts to the bottom.
Basically you just write a TextWriter
implementation and hook it up to your MVC base page that looks for <script src="
and captures the file name in an internal Queue
, then when it starts to get Write
calls for </body>
it renders everything built up in its Queue
. It could be done via regex but its probably pretty slow. This article shows an example of a TextWriter
for moving ViewState but the same principal should apply.
In order to override for dependencies I then defined script files and dependent script files in my web.config, similar to this in situations where I needed ordering override:
<scriptWriter>
<add file="~/scripts/jquery.ui.js">
<add dependency="~/scripts/jquery.js" />
</add>
</scriptWriter>
Disclaimer Like I said, this is hacky, the better solution would be to use some sort of CommonJS / AMD like syntax in your partials (@Script.Require("~/scripts/jquery-ui.js")
), basically you could write a function that if the master/layout page indicates its capturing script registration it can listen for all the child registrations, otherwise it can just output inline, so wouldn't hurt to just use it everywhere. Of course it may break intellisense.
So assuming some code in your master like:
@using(Script.Capture()) {
@RenderBody()
@Html.Partial("Partial")
}
And a partial of:
@Script.Require("~/scripts/jquery-ui.js")
Then you could just code something like this to handle it:
public class ScriptHelper : IDisposable
{
bool _capturing = false;
Queue<string> _list = new Queue<string>();
readonly ViewContext _ctx;
public ScriptHelper Capture()
{
_capturing = true;
return this;
}
public IHtmlString Require(string scriptFile)
{
_list.Enqueue(scriptFile);
if (!_capturing)
{
return Render();
}
return new HtmlString(String.Empty);
}
public IHtmlString Render()
{
IHtmlString scriptTags;
//TODO: handle dependencies, order scripts, remove duplicates
_list.Clear();
return scriptTags;
}
public void Dispose()
{
_capturing = false;
_ctx.Writer.Write(Render().ToHtmlString());
}
}
You may need to make the Queue
ThreadStatic
or use the HttpContext
or something, but I think this gives the general idea.