根據業務邏輯在服務端決定是否引入某 JS 文件(如權限控制、A/B 測試、動態合並)。
public static void RegisterScript(Page page, string url)
{
var script = new HtmlGenericControl("script");
script.Attributes["type"] = "text/javascript";
script.Attributes["src"] = url;
page.Header.Controls.Add(script);
}
protected void Page_Load(object sender, EventArgs e)
{
if (User.HasPermission("AdvancedFeature"))
RegisterScript(this, "/scripts/advanced.js");
}
<head runat="server">,否則 page.Header 為 null。<head> 末尾,執行順序靠後。<body> 底部),可改用 Page.ClientScript.RegisterClientScriptInclude 或手動輸出 Literal。ClientScript.IsClientScriptIncludeRegistered 檢查。