Skip to content

Instantly share code, notes, and snippets.

@i-e-b
Created December 13, 2011 10:01
Show Gist options
  • Save i-e-b/1471489 to your computer and use it in GitHub Desktop.
Save i-e-b/1471489 to your computer and use it in GitHub Desktop.
Javascript defer by script file or script block (for MVC using ASPX view engine)
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.WebPages;
namespace Web.Extensions {
public static class JavascriptIncludeExtensions {
private const string JscriptIncludeViewdata = "__jsrq";
private const string JscriptDeferViewdata = "__jsdf";
/// <summary>
/// Include a javascript url to be written by the RenderScripts method.
/// Url will be included exactly once no matter how many times this method is called.
/// </summary>
public static void RequireScript (this HtmlHelper html, string scriptLocation) {
string jsTag = "<script type=\"text/javascript\" src=\"" + scriptLocation + "\"></script>";
var jscripts = html.ViewContext.TempData[JscriptIncludeViewdata] as List<string> ?? new List<string>();
if (!jscripts.Contains(jsTag)) jscripts.Add(jsTag);
html.ViewContext.TempData[JscriptIncludeViewdata] = jscripts;
}
/// <summary>
/// Defer a script block (or any other HTML string) until RenderScripts is called.
/// Defered blocks always render after included script sources.
/// Call like: &lt;% Html.DeferBlock(()=> { %> &lt;script>...&lt;/script> &lt;% }); %>
/// </summary>
public static void DeferBlock (this HtmlHelper html, Action script) {
var jsActions = html.ViewContext.TempData[JscriptDeferViewdata] as List<Action> ?? new List<Action>();
jsActions.Add(script);
html.ViewContext.TempData[JscriptDeferViewdata] = jsActions;
}
/// <summary>
/// Render all defered scripts at this point. Defered scripts list will be reset.
/// </summary>
public static void RenderScripts (this HtmlHelper html) {
var jscripts = html.ViewContext.TempData[JscriptIncludeViewdata] as List<string>;
var jsActions = html.ViewContext.TempData[JscriptDeferViewdata] as List<Action>;
if (jscripts != null) {
html.ViewContext.Writer.Write(string.Join("\r\n", jscripts.ToArray()));
}
if (jsActions != null)
foreach (var action in jsActions) {
action();
}
html.ViewContext.TempData[JscriptDeferViewdata] = new List<Action>();
html.ViewContext.TempData[JscriptIncludeViewdata] = new List<string>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment