Custom javascript

Possible duplicate:
JavaScript function definition in ASP User Control

Hi,

I have a common user control that will be used twice on a page. It is associated with JavaScript, which also needs to be added. How can I add this to the page since javascript will be added several times.

+1
source share
3 answers

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

In OnLoad or OnInit of your user control, you want to call the following

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

No matter how many instances of the user control are on the page, the script will be included only once.

BTW, the Page.RegisterClientScriptxxx methods are now deprecated, preferably the ClientScriptManager.

+6
source

I assume this is ASP.NET. If so, inside your code, you call RegisterClientScriptBlock and pass the key to it. But before the call, you call IsClientScriptRegistered to check if this key has already been registered. This way, only the first user control to be added will register its javascript, so it will only be added to the page once.

+1
source

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

0
source

Source: https://habr.com/ru/post/1306396/


All Articles