开发者

Avoid that script in MasterPage and in Iframe child page is executed twice

I have developed a script with jQuery that everytime a <select> selection is changed then some logic is executed.

Initially I added that script to the MasterPage, in order to be sure that every page would be considered - however, I have some external pages开发者_运维问答 (aspx) that do not use the MasterPage and, as consequence, don't have the script.

To solve this I added the same script to a custom control, that is rendered as a <select> and is also present in those external pages. Unfortunately in this way the script is executed twice, instead of just once.

How can I change my code in order to ensure that the script would be executed in every page, but just once?


user .net's ClientScriptManager.RegisterClientScriptInclude, it has a key parameter, so it will only register each key once. In your masterpage and user control, just make sure you register them using the same key.

You could also use jquery to see if it is already registered and add id:

function requireOnce(url) {    
    if (!$("script[scr='" + url + "']").length) {
        $('head').append("<script type='text/javascript' src='" + url + "'></script>"); 
    }
}

above was taken from here


If you are using the encapsulating control which includes the script then remove the original script from the Master and use the said control in both pages. Unless I missed something, this is to say:

  • Remove original script from MasterPage
  • Use custom control with script in MasterPage
  • Use custom control with script in non-mastered pages.


I didn't want asp.net to handle my JavaScript, so I created a global variable isPostBack and set it to false by default. When the page did his postback I added window.isPostBack = true; to the page. Now your javascript only has to check the global variable (if(window.isPostBack){...}).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜