a DotNetStyling - .Net World by Armen Ayvazyan : Issue of Rendering JavaScript in WebControls
Welcome to DotNetStyling Sign in | Join | Help
Add to Technorati Favorites Add to Google Reader or Homepage Add to My AOL Subscribe in FeedLounge Subscribe in Bloglines Add to Excite MIX Add to flurry Add to Pageflakes Subscribe in NewsGator Online


Issue of Rendering JavaScript in WebControls

Originally I was not planning to post this subject until I spent hours for hunting some ghost JavaScript code. Problem was in generating custom JavaScript inside of WebControl.

Basically this is not about "How" to generate JavaScript code but "When". Unfortunately I faced to this problem several times and all the time it was a cause for some JavaScript bug.

 

Issue

During WebControl implementation developers used to register all necessary JavaScript code inside of OnLoad method. For instance:

 

private string GenerateJavaScript()

     StringBuilder sb = new StringBuilder(200);

     sb.AppendLine("var myBlogAddress = 'This is a test';");

     return sb.ToString();
}

protected override void OnLoad(EventArgs e)

     base.OnLoad(e);

     Page.ClientScript.RegisterStartupScript( 
           this.GetType(), 
           "variables"
           GenerateJavaScript(), 
           true);
}

 

What is wrong here?

When we hide this control on a page JavaScript will be still generated. OnLoad() method of control executes always even if Visibile property of control is set to false. It means that all code hosted inside of OnLoad() method will be executed even if control won't be shown on a page. As a result we have generated JavaScript code for something which doesn't exist on a page.

 

Solution

Move JavaScript registration to Render() or RenderContents(). Unlike OnLoad() method Render() or RenderContents() won't be executed in case when control is hidden on a page. As a result JavaScript code will be generated only in case when control is visible.

 

protected override void Render(HtmlTextWriter writer)
{
     base.Render(writer);

     Page.ClientScript.RegisterStartupScript( 
           Page.GetType(),
           "variables"
           GenerateJavaScript(), 
           true);
}

 

Technorati tags: , , ,

kick it on DotNetKicks.com Digg!

Share this post :

Posted: 5. listopadu 2007 9:42 by Armen Ayvazyan
Filed under: , ,

Comments

New Comments to this post are disabled