How2:在HttpModule中挂钩什么事件将js链接放入head元素

时间:2009-04-27 09:38:21

标签: asp.net ihttpmodule

我想让HttpModule从一些简单的配置数据中注入javascripts,css链接到HEAD元素。我不确定应该挂哪个事件?

我可以使用
- context.PreRequestHandlerExecute用于动态更改母版页 - 用于SEO优化的Context.BeginRequest

HTTPModule Event Execution Order?

有一些帮助

感谢任何提示。干杯,X。

3 个答案:

答案 0 :(得分:7)

using System;
using System.Web;
using System.Web.UI;

namespace YourNamespace
{
    public class YourModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += Application_PreRequestHandlerExecute;
        }

        private void Application_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            Page page = HttpContext.Current.CurrentHandler as Page;
            if (page != null)
            {
                string script = "/js/jquery.1.3.2.min.js";
                if (page.Header != null)
                {
                    string scriptTag = String.Format("<script language=\"javascript\" type=\"text/javascript\" src=\"{0}\"></script>\n", script);
                    page.Header.Controls.Add(new LiteralControl(scriptTag));
                }
                else if (!page.ClientScript.IsClientScriptIncludeRegistered(page.GetType(), script))
                    page.ClientScript.RegisterClientScriptInclude(page.GetType(), script, script);
            }
        }

        public void Dispose() { }
    }
}

ASP.Net生命周期:http://msdn.microsoft.com/en-us/library/ms178473.aspx

答案 1 :(得分:1)

这是我如何在没有HttpModule的情况下实现您正在做的事情。我不喜欢httpmodule的想法,因为如果我忘记注册它并且它没有运行,我的应用程序将无法工作,这将是一个非显而易见的错误。页面绝对需要包含JS,所以我决定把它放在项目的基页面类中。

我多年前实现了,并希望能够包含更多脚本,它支持css,元标记等....我忘了为什么我使用Page.Header.Controls.Add而不仅仅是Page。 ClientScript.RegisterClientScriptInclude但有一个原因。

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;

namespace YourNamespace
{
    public class HeaderIncludesManager
    {
        private List<string> m_IncludedFiles = new List<string>();

        public void IncludeScript(string s)
        {
            IncludeScript(s, null);
        }

        public bool IsIncluded(string file)
        {
            return (m_IncludedFiles.Find(s => s.Equals(file, StringComparison.InvariantCultureIgnoreCase)) != null);
        }

        public void IncludeScript(string script, string condition)
        {
            Page page = HttpContext.Current.CurrentHandler as Page;
            if (!IsIncluded(script) || page == null)
                return;

            string scriptFile = string.Format("/{0}/{1}?v={2}", MyConfig.JSDir, script, MyConfig.BuildNumber);
            if (page.Header != null)
            {
                string scriptTag = String.Format("<script language=\"javascript\" type=\"text/javascript\" src=\"{0}\"></script>\n", scriptFile);
                if (!String.IsNullOrEmpty(condition))
                    scriptTag = String.Format("<!--[{0}]><script language=\"javascript\" type=\"text/javascript\" src=\"{1}\"></script><![endif]-->\n", condition, scriptFile);

                page.Header.Controls.Add(new LiteralControl(scriptTag));
                m_IncludedFiles.Add(script);
            }
            else if (!page.ClientScript.IsClientScriptIncludeRegistered(GetType(), scriptFile))
            {
                page.ClientScript.RegisterClientScriptInclude(GetType(), scriptFile, scriptFile);
                m_IncludedFiles.Add(script);
            }
        }

        public void IncludeCss(string css)
        {
            Page page = HttpContext.Current.CurrentHandler as Page;
            if (!IsIncluded(css) || page == null)
                return;

            string cssfile = string.Format("/{0}/{1}?v={2}", MyConfig.CssDir, css, MyConfig.BuildNumber);
            if (page.Header != null)
            {
                ((Page)HttpContext.Current.CurrentHandler).Header.Controls.Add(new LiteralControl(String.Format("<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />\n", cssfile)));                    
                m_IncludedFiles.Add(css);
            }
        }

        public void IncludeJQuery()
        {
            IncludeScript("jquery-1.2.3.min.js");
        }

        public void IncludeJQueryUI()
        {
            IncludeJQuery();
            IncludeScript("jquery.ui.1.0.min.js");
            IncludeCss("jquery-theme.css");
        }

        public void IncludeFlotScripts()
        {
            IncludeJQuery();
            IncludeScript("flot/jquery.flot.js");
            IncludeScript("flot/excanvas.pack.js", "if IE");
        }
    }

    public class MyPage : Page
    {
        public HeaderIncludesManager HeaderIncludes = new HeaderIncludesManager();
    }

    public class MyControl : UserControl
    {
        public new MyPage Page
        {
            get
            {
                return (MyPage)base.Page;
            }
        }
    }

    public class SomeControlThatNeedsScripts : MyControl
    {
        protected override void OnLoad(EventArgs e)
        {
            Page.HeaderIncludes.IncludeJQueryUI();
            base.OnLoad(e);
        }
    }
}

答案 2 :(得分:0)

对于这种类型的功能,HttpHandler将是更好的选择。这是一个结合css和javascript文件的例子;这不是你想要的,但应该让你朝着正确的方向前进:http://www.codeproject.com/KB/aspnet/HttpCombine.aspx