开发者

User control javascript [duplicate]

开发者 https://www.devze.com 2022-12-24 08:57 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: JavaScript Function Definition in ASP User Control
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

JavaScript Function Definition in ASP User Control

Hi,

I have a gene开发者_StackOverflowric 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.


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消