Skip to content

Instantly share code, notes, and snippets.

@house9
Created March 16, 2011 01:32
Show Gist options
  • Save house9/871851 to your computer and use it in GitHub Desktop.
Save house9/871851 to your computer and use it in GitHub Desktop.
using System;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
public static class HtmlHelperExtensions
{
/// <summary>
/// render script tag to include javascript file from cdn, but fallback to local if cannot be loaded
/// </summary>
/// <param name="helper"></param>
/// <param name="cdnPath">start with // to handle either http or https</param>
/// <param name="localPath">start with ~/</param>
/// <param name="javascriptCondition">javascript condition, if true then your browser will load the local file</param>
/// <returns>
/// <script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
/// <script>!window.jQuery && document.write(unescape('%3Cscript src="/Scripts/jquery-1.4.4.min.js"%3E%3C/script%3E'))</script>
/// </returns>
/// <seealso cref="http://paulirish.com/2010/the-protocol-relative-url/"/>
public static MvcHtmlString JavascriptIncludeFromCdnWithFallback(this HtmlHelper helper, string cdnPath, string localPath, string javascriptCondition)
{
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
var cdnBuilder = new TagBuilder("script");
var localBuilder = new TagBuilder("script");
// src for cdn resource
cdnBuilder.Attributes.Add("src", cdnPath);
// js to build a local script tag if needed
localBuilder.InnerHtml = String.Format
(
"{0} && document.write(unescape('%3Cscript src=\"{1}\"%3E%3C/script%3E'))",
javascriptCondition,
urlHelper.Content(localPath)
);
// return markup
var built = String.Format("{0}\n\t{1}", cdnBuilder.ToString(TagRenderMode.Normal), localBuilder.ToString(TagRenderMode.Normal));
return MvcHtmlString.Create(built);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment