views:

742

answers:

3

Hi,

I've a specific requirement of rendering Javascript onto a master page of an asp.net site. There are two specific requirements of it:

1) The position - It should be rendered at the very end of the page just before BODY tag 2) Control - Render it only when requested.

I solved #2 by creating a web-part which will render the javascript only when its placed on the page. But I could not achieve #1 since the web part doesn't give me control over where to render the javascript inside body tag.

Did anyone solve this problem before?

Please advice.

Thanks Sachit

+1  A: 

Try using ClientScript.RegisterStartupScript, it injects the script right above the </body> tag.

Josh Stodola
That gives me only control over when to render....but not where to render....Both are important requirements for me :(
@Sachit - if by "where" you mean which pages to render it on...I would suggest having a helper function that registers the script, then programmatically call the helper function on pages that need to render it.
JustLoren
actually by where I meant the exact location of the script. I need this script to be the one just above </body> tag. I think I can get close to this by using ClientScript.RegisterStartupScript but looks like I can not control the order of scripts if I've multiple which is a problem since I've many scripts on that page and I want this one to be at the bottom.
If you have multiples, use a Strinbuilder to combine them in the order you need, and then use this.
Josh Stodola
actually let me tell rest of the story....this is a sharepoint master page, so I've no control over what and how SharePoint renders rest of the scripts, styles etc...
A: 

RenderControl is the last method to return in MasterPage Event Lifecycle that you can override. My guess would be to put it there.

CptSkippy
A: 

If you are using Master Page, then why not put a content place holder just before the end body tag? The content pages should render their JavaScript in that particular place holder.

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Base.master.cs" Inherits="Common.Base" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">    


    <asp:ContentPlaceHolder ID="headerContent" runat="server"/>
</head>
<body>
    <form id="mainForm" runat="server">
        <asp:ContentPlaceHolder ID="mainContent" runat="server" /> 
        <asp:ContentPlaceHolder ID="footerContent" runat="server" />       
    </form>    

    <asp:ContentPlaceHolder ID="footerJsContent" runat="server"/>
</body>
</html>

Content pages should render their JavaScript inside the footerJsContent place holder.

SolutionYogi