Asp.net provides javascript loading only once

I work in asp.net webforms and I create a UserControl which depends on a small amount of javascript that resides in an external file.

I want to be able to reference javascript inside the UserControl to make sure it loads on the page, but the problem is that UserControl can appear several times on the page, so I only want the script to load with the first instance of UserControl.

Is there an easy way to do this in ASP.NET Web formats?

+6
javascript webforms
source share
3 answers

Use the ClientScriptManager RegisterClientScript() methods to handle this. In your case, since you are including the script from an external file, use RegisterClientScriptInclude() .

Alternatively, if you are using UpdatePanels, use the ScriptManager equivalent methods of Register...() .

+9
source share

You can also deal with this problem in the JS file itself if you control its contents.

 var myObj = myObj || {}; // Variable to namespace your work // Make sure we do our work only once if (!(myObj.token)) { // do our work here... myObj.token = {}; // this ensure we won't enter the if block the next time } 
0
source share

Link to the script in the HEAD of the page itself.

 <html> <head> ... <script src="<name of file>" type="text/javascript"></script> ... </head> <body> ... </body> </html> 
-2
source share

All Articles