Reputation: 52942
I have a method that does something, and it puts a javascript method into the page that it uses. I need to make sure that it only puts the javascript method in once regardless of how many times it is called.
What's the best way to do this? Can I search the section of page that has rendered so far and see if the method was already created?
Upvotes: 0
Views: 274
Reputation: 3074
Use an external JS file and embed it once - put all the js you require in it. Then attach all the events unobtrusivly. This mean that events are attached when needed and functions can only ever be included once. This avoids having the program round the problem too.
Upvotes: 0
Reputation: 12589
I think what you want to look at are the IsClientScriptBlockRegistered / IsStartupScriptRegistered
methods of the ClientScriptManager object, which allow you to check if you've already put some script with a key onto the page e.g.
Dim myScriptKey As String = "myScriptBlock"
Dim myScript As String = "<script type='javascript'>alert('Hello world');</script>"
If Page.ClientScript.IsClientScriptBlockRegistered(myScriptKey) Then
'We've already output some script with this key to the page so don't put it out again
Else
Page.RegisterClientScriptBlock(type:=GetType(Me), key:=myScriptKey, script:=myScript, addScriptTags:=False)
End If
Upvotes: 2
Reputation: 54605
Is this server side or is a javascript method inserting another javascript method?
If the latter just check for the function name e.g. you somewhere create function onlyOnce() {...}
. Then just do
if(onlyOnce = undefined) {
//insert method
}
Upvotes: 0
Reputation: 10748
If your server side technology is asp.net, you can make the call in the page load event and wrap it in a !Page.IsPostback
block. I would guess many(most) server side technologies have something similar.
Upvotes: 0