Are top-level script blocks executed twice?

I tried to figure out how this is possible. Therefore, 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 some reason, which must be executed once, it is actually executed twice. When debugging under Firebug, I actually have one step before the warning new x variable , and at that moment it will display two warnings at once. Subsequently, it proceeds to x exists , as if two separate threads were executing the same code. This does not occur in Internet Explorer 8, but occurs in Chrome and Firefox (recent versions from this date).

So this is what the warnings are:

  • should run once
  • new variable x
  • should run once
  • x exists

I know I could get around this by wrapping everything in the has_run variable, but I would rather understand what is going on here.

The script block is not registered or something else, it is explicitly set via the Literal control. In addition, there is an UpdatePanel on the page, but this script block is not part of the UpdatePanel, and I confirmed that the UpdatePanel is not updating. I triple checked that this code only in my HTML once. And no other HTTP requests (e.g. for UpdatePanel) are made when it loads. Just a few jQuery.ajax downloads.

How is this possible? How to fix it?

+4
source share
2 answers

I figured it out with @mikemanne

jQuery.dialog will move the div dialog to the DOM. So this means that it forces it to run twice, possibly in a different thread causing erratic behavior.

Example: http://jsbin.com/akacah

+2
source

var x = true; rises above the expression if!

-1
source