Simple ASP.NET Control To Move jQuery Script

I'm using jQuery on my web site, and I wanted have my in-place jQuery script automatically put into the <head> of the HTML document. The reason I needed this was the the form the jQuery was used for (the comments form for this web site!) was in a control and I'm using ASP.NET directives to populate the control references. Since this is done within the control I had to wait until after that was done to move the script.

Just add this control below to your project and then you can do things like this:

<website:JQueryInjector ID="FormValidate" runat="server">

        <script language="javascript" type="text/javascript">
            $(document).ready(function() {.. </script> </website:JQueryInjector>

public class JQueryInjector : HtmlContainerControl
{
    public JQueryInjector()
    {
    }

    protected override void OnPreRender(EventArgs e)
    {
        if (Site != null && Site.DesignMode)
        {
            return;
        }

        using (StringWriter script = new StringWriter())
        using (HtmlTextWriter writer = new HtmlTextWriter(script))
        {
            RenderChildren(writer);
            Page.Header.Controls.Add(new LiteralControl(script.ToString()));
        }
        base.OnPreRender(e);
    }

    protected override void Render(HtmlTextWriter writer)
    {
        // Do nothing.
    }
}

About this entry