有条件地添加外部CSS/Javascript链接

本文关键字:Javascript 链接 CSS 外部 添加 有条件 | 更新日期: 2023-09-27 18:16:40

我需要添加链接到一个ASPX页的头部基于服务器端函数从母版页的Page_Load()被调用。整个网站都在使用同一个主页

最好的方法是什么?

<head>中的<asp:Literal>控制?

有条件地添加外部CSS/Javascript链接

可能太晚了,但下面的方法有一个优点,即永远不会添加相同的脚本两次。

public static void RegisterClientScriptInclude(Page page, string name, string url)
{
    Type cstype = page.GetType();
    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = page.ClientScript;
    // Check to see if the include script exists already.
    if (!cs.IsClientScriptIncludeRegistered(cstype, name))
    {
        cs.RegisterClientScriptInclude(cstype, name, page.ResolveClientUrl(url));
    }
}

如果你在需要的基础上从不同的用户控件添加外部javascript文件,

会派上用场。

有很多方法可以做到这一点:

  1. Page_Load方法中,以编程方式访问母版页的页眉,如:

    HtmlGenericControl style = new HtmlGenericControl("link");
    style.Attributes.Add("href", "path-to-your-style");
    style.Attributes.Add("rel", "stylesheet");
    style.Attributes.Add("type", "text/css");
    this.Page.Header.Controls.AddAt(0, style);
    
  2. 第二种方法是把runat='server'属性放在你的条件样式上,在你的Page_Load方法中,打开或关闭它们的可见性:

    <link type='text/css' rel='stylesheet' href='path-to-css-file' 
    runat='server' id='cssFile' />
    

    然后在你的Page_Load中你有:

    if (conditionIsNotMet)
    {
        cssFile.Visible = false;
    }
    

我以前做过这样成功的事情。

<link rel="Stylesheet" type="text/css" href="<%= System.Configuration.ConfigurationManager.AppSettings["dhxStyle"] %>" />