views:

53

answers:

3

Hi,

I have a generic user control which will be used twice in a page. There is a javascript asscoiated with it which also needs to be added. How can I add this to a page since the javascript will be added multiple times.

A: 

I would suggest that you make the javascript source separate from the control, then load the javascript once before you load the control twice.

JMTyler
+1  A: 

I'm assuming this is ASP.NET. If so, within your code, you call RegisterClientScriptBlock and pass it a key. But before the call, you call IsClientScriptRegistered to check whether that key has already been registered. That way, only the first user control that is added will register its javascript, so it will only be added to the page once.

JacobM
+2  A: 

The ClientScriptManager is what you are looking for it has a set of RegisterClientScriptxxx methods for registering strings/include file/resources etc. as client script blocks. Each of these methods takes arguments of a key and optionally a type, the script with each key/type are only included once.

In the OnLoad or OnInit of your user control you want a call like the following

Page.ClientScriptManager.RegisterClientScriptInclude(typeof(MyUserControl), "myscript", @"/path/to/my/script.js");

No matter how many instances of the user control are in the page the script will only get included once.

BTW, Page.RegisterClientScriptxxx methods are now deprecated, ClientScriptManager is preferred.

ScottS
Thanks -- it's been a number of years since I was involved with ASP.NET; probably should have checked for such changes.
JacobM