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);
}
