ASP.NET MVC 移除 WebForms 的 ScriptManager 後,開發者需自行解決腳本重複引用、載入順序、衝突等問題。本文提出一個極簡的 HtmlHelper 擴充方案,透過 HttpContext.Items 去重,在 Master Page `
public static class ScriptManagementExtension
{
private const string ScriptFormat = "\t<script src=\"{0}\" type=\"text/javascript\"></script>";
private const string CSSFormat = "\t<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\"></link>";
private static string IncludeHeader(HtmlHelper helper, string key, string path, string format)
{
var context = helper.ViewContext.HttpContext;
if (!context.Items.Contains(key))
{
var url = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection);
context.Items[key] = true;
return string.Format(format, url.Content(path));
}
return null;
}
public static string IncludeScript(this HtmlHelper helper, string path)
=> IncludeScript(helper, path.ToLower(), path);
public static string IncludeScript(this HtmlHelper helper, string key, string path)
=> IncludeHeader(helper, key, path, ScriptFormat);
public static string IncludeCSS(this HtmlHelper helper, string path)
=> IncludeCSS(helper, path.ToLower(), path);
public static string IncludeCSS(this HtmlHelper helper, string key, string path)
=> IncludeHeader(helper, key, path, CSSFormat);
}
在 Master Page `
` 區域放置佔位符:<asp:ContentPlaceHolder ID="ScriptContent" runat="server" />
各 View 中直接呼叫:
<%= Html.IncludeCSS("https://www.cnblogs.com/Content/Site.css") %>
<%= Html.IncludeCSS("jQuery_Theme", Html.GetThemePath()) %>
<%= Html.IncludeScript("https://www.cnblogs.com/Scripts/jquery-1.3.2.min.js")%>
...
UrlHelper.Content 自動解析 ~ 路徑。| 方案 | 複雜度 | 輸出位置 | 去重機制 | 備註 |
|---|---|---|---|---|
| CodePlex 專案 | 高 | Body 底部 | 字典管理 | 需在 Master Page 末尾呼叫 Render |
| jQuery UI Extensions | 中 | Body | 字典 | 綁定特定 UI 庫 |
| 本方案 | 極低 | Head | HttpContext.Items | 單一靜態類別,即用即走 |
為何 Microsoft 至今未內建標準腳本管理解決方案?或是已存在但未被廣泛發現?期待社群補充。