Created
March 16, 2011 01:32
-
-
Save house9/871851 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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