views:

45

answers:

2

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?

+1  A: 

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
This makes more sense and it is pretty common practice too.
Raja
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
A: 

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
This would go in the codebehind, anytime is acceptable, the ClientScript wont render it until the Render phase
Glennular
Shouldn't it be 'if not registered' instead of 'if registered'?
Steven
Thanks for catching my typos!
Glennular
Also, what is tType?
Steven
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