开发者

Top level script blocks executed twice?

I've been trying to figure out how this is even possible. So I have an ASP.Net website. In the rendered HTML something like

<script type="text/javascript">
alert('should run once');
if(x === undefined){
  var x=true;
  alert('new x variable');
}else{
  alert('x exists');
}
</script>

However, for whatever reason what should run once, actually runs twice. When debugging under Firebug, I actually single 开发者_运维问答step up to the alertnew x variable and at that point it will appear to display two alerts at once. Afterwards, it skips to x exists as if there are two separate threads running this same code. This does not occur in Internet Explorer 8, but does occur in Chrome and Firefox (latest versions as of this date)

So this what the alerts spit out as:

  1. should run once
  2. new x variable
  3. should run once
  4. x exists

I know I could workaround it by wrapping everything in a has_run variable, but I'd prefer to understand what is going on here.

The script block is not registered or anything, it is inserted plainly through a Literal control. Also, there is an UpdatePanel on the page, but this script block is not within the UpdatePanel, and I've confirmed that no UpdatePanel is doing a refresh. I've triple checked that this code is only in my HTML once. And no other HTTP requests(such as for an UpdatePanel) is being made when this loads. Just a few jQuery.ajax loads.

How is this even possible? How do I fix it?


I've figured this out with the help of @mikemanne

jQuery.dialog will move the dialog div in the DOM. So what this means is that it causes it to get executed twice, apparently possibly in a different thread causing erratic behavior.

An example: http://jsbin.com/akacah


var x = true; is hoisted above the if statement!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜