場景:在自定義控件、用戶控件、頁面、後台代碼都會有引用JS的可能,這就會出現混亂或者重復引用的可能。
一個自定義控件,用於在ASPX頁面中注冊JS:
public class Script : Control
{
#region 屬性
private string m_Src;
/// <summary>
/// 腳本文件路徑
/// </summary>
public string Src
{
get { return m_Src; }
set { m_Src = value; }
}
#endregion
/// <summary>
/// 在控件Init的時候將JS路徑添加到HttpContext.Current.Items["IncludedJavaScript"]中。
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (!string.IsNullOrEmpty(Src))
{
string src = ResolveUrl(Src);
List<string> includedJs = HttpContext.Current.Items["IncludedJavaScript"] as List<string>;
if (null == includedJs)
{
includedJs = new List<string>();
HttpContext.Current.Items["IncludedJavaScript"] = includedJs;
}
if (!includedJs.Contains(src))
{
includedJs.Add(src);
}
}
}
}