User control javascript

Possible Duplicate:
JavaScript Function Definition in ASP User Control

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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.

Method 3

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x