开发者

Stop your code injecting javascript twice?

开发者 https://www.devze.com 2022-12-12 17:47 出处:网络
I have a method that does something, and it puts a开发者_JS百科 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

I have a method that does something, and it puts a开发者_JS百科 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?


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


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.


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
} 


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.

0

精彩评论

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

关注公众号