Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class DeferHtmlHelperExtensions
- {
- private const string DeferredScriptsKey = "deferredScripts";
- public static MvcHtmlString RenderDeferredScripts(this HtmlHelper htmlHelper)
- {
- var httpItems = htmlHelper.ViewContext.HttpContext.Items;
- if (!httpItems.Contains(DeferredScriptsKey)) return MvcHtmlString.Empty;
- var scripts = (IList<string>) httpItems[DeferredScriptsKey];
- var scriptBuilder = new StringBuilder(scripts.Sum(script => script.Length));
- foreach (var script in scripts.Where(script => !string.IsNullOrWhiteSpace(script)))
- scriptBuilder.AppendLine(script);
- return new MvcHtmlString(scriptBuilder.ToString());
- }
- public static MvcHtmlString Defer<TModel>(this HtmlHelper<TModel> htmlHelper, Func<HtmlHelper<TModel>, object> action)
- {
- var result = action(htmlHelper);
- string resultString = result is IHtmlString ? ((IHtmlString) result).ToHtmlString() : result.ToString();
- string html, script;
- ExtractScript(resultString, out html, out script);
- if (!String.IsNullOrWhiteSpace(script))
- {
- var httpItems = htmlHelper.ViewContext.HttpContext.Items;
- if (!httpItems.Contains(DeferredScriptsKey)) httpItems.Add(DeferredScriptsKey, new List<string>());
- var scripts = (IList<string>) httpItems[DeferredScriptsKey];
- scripts.Insert(0, script);
- }
- return new MvcHtmlString(html);
- }
- private static void ExtractScript(string input, out string html, out string script)
- {
- html = script = null;
- if (String.IsNullOrWhiteSpace(input)) return;
- var htmlBuilder = new StringBuilder();
- var scriptBuilder = new StringBuilder();
- bool isInScript = false;
- const string scriptOpen = "<script";
- const string scriptClose = "</script";
- for (int i = 0; i < input.Length; i++)
- {
- var c = input[i];
- if (c == '\r' || c == '\n') continue;
- if (isInScript)
- {
- if (IsSequentialMatch(input, i, scriptClose))
- {
- scriptBuilder.Append("</script>");
- var closeIndex = input.IndexOf('>', i);
- if (closeIndex == -1) break;
- i = closeIndex;
- isInScript = false;
- continue;
- }
- scriptBuilder.Append(c);
- continue;
- }
- if (IsSequentialMatch(input, i, scriptOpen))
- {
- isInScript = true;
- scriptBuilder.Append(c);
- continue;
- }
- htmlBuilder.Append(c);
- }
- html = htmlBuilder.ToString().Trim();
- script = scriptBuilder.ToString().Trim();
- }
- private static bool IsSequentialMatch(string input, int inputStartIndex, string toMatch)
- {
- if (input == null || toMatch == null || inputStartIndex < 0 || inputStartIndex >= input.Length) return false;
- for (int i = inputStartIndex; i < inputStartIndex + toMatch.Length; i++)
- if (!input[i].Equals(toMatch[i - inputStartIndex])) return false;
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement