Javascript in my usercontrols at the bottom please

So the other day I sat down to optimize my latest part of a page that I been working on and I realized that I had some javascript in a usercontrol. In the javascript I called .net functions like ResolveUrl and i didn't want the cost of yet another request with the thoughts of all my jquery plugins.

So what was my solution, well after a couple of bad ones I found a very smart one if I may say so myself :) I used one of my loves HtmlTextWriter and RenderControl.

 UserControl:

<asp:placeholder id="phr" runat="server">

<script type="text/javascript">......</script>

</asp:placeholder>

So I put my javascript in a placeholder in my usercontrol.

UserControl Codebehind:

protected void Page_Load(......) {

    var key = this.ID + "_script";
    var stream = new StringWriter();
    phr.RenderControl(new HtmlTextWriter(stream));
    phr.Visible = false;

    if (!Page.ClientScript.IsStartupScriptRegistered(key))
        Page.ClientScript.RegisterStartupScript(Page.GetType(), key, stream.ToString().Replace("\n", "").Replace("\r", "").Replace("\t", ""));

}

And here i render my placeholder to a string then hides it so it won't render at the usercontrols place on the page. Then i use the scriptmanager in a webform page, but you can build this in mvc / asp.net(without webforms) to without a scriptmanager and you minified the script with replace ;) This way you follow the yahoo tip to render javascript at the bottom of the page and in only one request.

I hope someone out there have use of this :)

Comments

Add comment

Name:

Mail:

Website:

Comment:


<< [1] >>
    << [1] >>