19

We have a nested layout for our various pages. For example:

Master.cshtml

<!DOCTYPE html>
<html>
   <head>...</head>
   <body>@RenderBody()<body>
</html>

Question.cshtml

<div>
  ... lot of stuff ...
  @Html.Partial("Voting", Model.Votes)
</div>
<script type="text/javascript">
  ... some javascript ..
</script>

Voting.cshtml

<div>
  ... lot of stuff ...
</div>
<script type="text/javascript">
  ... some javascript ..
</script>

This all works fine, but I would like to push all of the JavaScript blocks to be rendered in the footer of the page, after all the content.

Is there a way I can define a magic directive in nested partials that can cause the various script tags to render in-order at the bottom of the page?

For example, could I create a magic helper that captures all the js blocks and then get the top level layout to render it:

Voting.cshtml

<div>
  ... lot of stuff ...
</div>
@appendJSToFooter{
   <script type="text/javascript">
     ... some javascript ..
   </script>
}
3
  • Your real problem is the lack of composability in the view engine. Feb 17, 2012 at 13:36
  • @MauricioScheffer totally agree, and the page evaluation order which is kind of crazy Feb 28, 2012 at 5:36
  • 1
    @SamSaffron you ever find a good pattern for this?
    – Paul Tyng
    Mar 15, 2012 at 15:57

11 Answers 11

3

I came up with a relatively simple solution to this problem about a year ago by creating a helper to register scripts in the ViewContext.TempData. My initial implementation (which I am in the process of rethinking) just outputs links to the various referenced scripts. Not perfect but here's a walk-through of my current implementation.

On a partial I register the associated script file by name:

@Html.RegisterScript("BnjMatchyMatchy")

On the main page I then call a method to iterate the registered scripts:

@Html.RenderRegisteredScripts()

This is the current helper:

public static class JavaScriptHelper
{
    private const string JAVASCRIPTKEY = "js";

    public static void RegisterScript(this HtmlHelper helper, string script)
    {
        var jScripts = helper.ViewContext.TempData[JAVASCRIPTKEY]
            as IList<string>; // TODO should probably be an IOrderedEnumerable

        if (jScripts == null)
        {
            jScripts = new List<string>();
        }

        if (!jScripts.Contains(script))
        {
            jScripts.Add(script);
        }

        helper.ViewContext.TempData[JAVASCRIPTKEY] = jScripts;
    }

    public static MvcHtmlString RenderRegisteredScripts(this HtmlHelper helper)
    {
        var jScripts = helper.ViewContext.TempData[JAVASCRIPTKEY]
            as IEnumerable<string>;

        var result = String.Empty;

        if (jScripts != null)
        {
            var root = UrlHelper.GenerateContentUrl("~/scripts/partials/",
                    helper.ViewContext.HttpContext);

            result = jScripts.Aggregate("", (acc, fileName) =>
                String.Format("<script src=\"{0}{1}.js\" " +
                    "type=\"text/javascript\"></script>\r\n", root, fileName));
        }

        return MvcHtmlString.Create(result);
    }
}

As indicated by my TODO (I should get around to that) you could easily modify this to use an IOrderedEnumerable to guarantee order.

As I said not perfect and outputting a bunch of script src tags certainly creates some issues. I've been lurking as your discussion about the jQuery Tax has played out with Steve Souders, Stack Overflow, Twitter and your blog. At any rate, its inspired me to rework this helper to read the contents of the script files and then dump them to the rendered page in their own script tags rather than link tags. That change should help speed up page rendering.

3
  • This is kind of close to where I am at ... there are ordering issues that are tricky, see: stackoverflow.com/questions/9303380/… and snipt.org/uNq8 Feb 17, 2012 at 6:23
  • @SamSaffron I see where you are headed. Not having to explicitly care about the ordering I hadn't thought much about it beyond "it'd probably be a good idea to ensure the order." Didn't realize the way in which Razor renders could muck up the order so bad. I'll keep an eye on your snipt and will sleep on this tonight. Maybe something will occur to me. ;)
    – ahsteele
    Feb 17, 2012 at 6:47
  • 3
    TempData is so wrong for this. TempData is made for preserving data to the next request! What you want is HttpContext.Current.Items.
    – usr
    Feb 17, 2012 at 22:34
1

Can you define a section at the bottom of the body element in your Master.cshtml file as follows:

@RenderSection("Footer", required: false)

Then in the individual .cshtml files you can use the following:

@section Footer {
    <script type="text/javascript">
    ...
    </script>
}
0
1

Rather than building some server-side infrastructure to handle a client-side concern, look at my answer to another question: https://stackoverflow.com/a/9198526/144604.

With RequireJS, http://requirejs.org, your scripts won't necessarily be at the bottom of the page, but they will be loaded asynchronously, which will help a lot with performance. Page rendering won't be halted while the scripts are executed. It also promotes writing Javascript as lots of small modules, and then provides a deployment tool to combine and minimize them when the site is published.

1

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.

2
  • This is kind of close to where I am at ... there are ordering issues that are tricky, see: stackoverflow.com/questions/9303380/… and snipt.org/uNq8 ... Feb 20, 2012 at 0:57
  • I think you should be able to handle the ordering issues by writing your own base pages, the base page can know whether its a layout or a partial, etc. So it doesn't need to know if its in RenderBody or RenderSurrounding, just needs to know that you are calling ExecutePageHierarchy and the type of page it is. You could probably also leverage smarter start pages.
    – Paul Tyng
    Feb 20, 2012 at 1:28
1

If you have a situation where you cannot improve on the existing structure (ie. you have both MVC and old WebForms pages, javascript tags are included all over the place, etc...), you could have a look at some work I'm doing on an HTTP Module that does postprocessing on the output, much like mod_pagespeed does in Apache. Still early days though.

https://github.com/Teun/ResourceCombinator

If you can still choose to include your scripts in a predefined way, that is probably better.

Edit: the project mentioned by Sam (see comments) was indeed largely overlapping and far more mature. I deleted the ResourceCombinator project from GitHub.

3
  • nice project! how is perf on your post processor? how do you ensure it does not minify stuff twice, etc Feb 28, 2012 at 21:03
  • also I hope you have seen requestreduce.com looks a bit more complete and open source as well Feb 29, 2012 at 1:26
  • Mmm, looks interesting indeed. Have to look further into this.
    – Teun D
    Feb 29, 2012 at 15:30
1

I realise this ship has pretty much sailed but since I have some kind of solution (albeit not a perfect one) I thought I'd share it.

I wrote a blog post about approaches to script rendering that I use. In that I mentioned a library written by Michael J. Ryan that I have tweaked for my own purposes.

Using this it's possible to render a script anywhere using something like this:

@Html.AddClientScriptBlock("A script", @"

    $(function() {
        alert('Here');
    });

")

And then trigger it's output in the layout page using this call just before the closing body tag:

@Html.ClientScriptBlocks()

You get no intellisense in Visual Studio using this approach. If I'm honest I don't really advise using this technique ; I'd rather have separate JS files for debug points and use HTML data attributes to drive any dynamic behaviour. But in case it is useful I thought I'd share it. Caveat emptor etc

Here's a list of relevant links:

  1. My blog post
  2. Michael J. Ryan's blog post
  3. My helper on GitHub
0

I would suggest that you shouldn't be putting scripts directly onto your page.

Instead pull the JavaScript into a separate .js file and then reference it in the header.

I know it is not exactly what you are asking for, but I assume you are doing this for SEO purposes, and this should have the same effect as putting the script at the bottom of the page.

1
  • this is nothing to do with SEO this is a performance thing, scripts at the head block Feb 15, 2012 at 3:32
0

We use the ScriptRegistrar method from Telerik's (GPL open sourced) Asp.Net MVC library.

SImply include your javascript in any views/partials pages etc. as below. The Telerik library handles rendering all of this this at the bottom of the final outputted page.

<% 
Html.Telerik().ScriptRegistrar()
             .Scripts(scripts => scripts.AddSharedGroup('lightbox')
             .OnDocumentReady(() => { %>
   <%-- LIGHTBOX  --%>
   $('.images a').lightBox();
<% });%>

It also looks after grouping multiple css and js includes together into single requests.

http://www.telerik.com/products/aspnet-mvc.aspx

0

My humble option is to leave these kind of things to the professionals :-) Take a look at ControlJS, a lib to load your external javascript files without interrupting the page processing (async, defer, on demand etc). With ControlJS it doesn't mind "where" you will put the loading code, they will all load at the end or on demand.

This presentation of Steve Souders, the lib author, gives a good overview of the problem (and the solution).

1
  • not sure how this even answers the question, I understand how the various async script loaders work, my current choice is github.com/wessman/defer.js cause you can simply defer load the defer loader as well. this is a specific issue with asp.net mvc. Feb 28, 2012 at 5:35
0

Sam,

I wrote Portal for this very reason: http://nuget.org/packages/Portal You basically put a

@Html.PortalOut() 

in your master / layout view and stuff HTML code in from views or partial views like this

@Html.PortalIn(@<text> $(function() { alert('Hi'); }); </text>)

You can use several "portals" by specifying a input and output key. Right now it adds code in the order it comes in (partials render first, from "top to bottom"). If you're in the same view you have to deal with the top to bottom restriction, i.e. you can't have an "out" portal before an "in" one, but this is not an issue when sending from views to layout. There are more examples in the Portal.cs file.

0

What about html Response Filter, that modifies your final html. Find all script tags before certain place and paste them at the end of body. It's also works for improving dataTables rendering, by marking them hidden initially and make js to show them.

No intervention or changes on actual code needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.