4

Possible Duplicate:
User control javascript

I defined a JavaScript function inside a user control.

If I have multiple instances of the user control on my .aspx page, how do I prevent multiple function definitions in the resulting HTML code?

Community
  • 1
  • 1
Steven
  • 13,501
  • 27
  • 102
  • 146

2 Answers2

2

You'll want to use the Page.ClientScript manager.

The following code will only register your code once per a page.

if (!page.ClientScript.IsClientScriptBlockRegistered(tType, "MyScript"))
{
     page.ClientScript.RegisterClientScriptBlock(tType, "MyScript", sScript);
}

You can also make sure that *.js files get added only once

if (!page.ClientScript.IsClientScriptIncludeRegistered(tType, "MyScriptFile"))
{
     page.ClientScript.RegisterClientScriptInclude(tType,"MyScriptFile","MyJavaScript.js")
}
Glennular
  • 17,827
  • 9
  • 58
  • 77
  • This would go in the codebehind, anytime is acceptable, the ClientScript wont render it until the Render phase – Glennular Apr 08 '10 at 18:32
  • Shouldn't it be 'if not registered' instead of 'if registered'? – Steven Apr 08 '10 at 18:39
  • Thanks for catching my typos! – Glennular Apr 08 '10 at 18:55
  • tType would be the type of the parent object to make a more unique key for your registered script. So you could use this.GetType(), so indicate the "MyScript" is specif to your Control's type. So you can have multiple "MyScript" JS blocks for different object types (or controls) – Glennular Apr 08 '10 at 19:23
1

Could you put the javascript code in a separate .js file and reference that common.js file from the web page or master page?

DOK
  • 32,337
  • 7
  • 60
  • 92
  • This makes more sense and it is pretty common practice too. – Raja Apr 08 '10 at 18:28
  • 2
    I disagree. The function should be defined in the user control instead of globally for code reusability. It would be like defining class member functions globally instead of within the class. – Steven Apr 08 '10 at 18:54