简体   繁体   中英

Why do you have to initialize global variables within the body tags and not the head

In javascript, when initializing global variables,

<head>
      <script type='text/javascript'>
       var globalvar = 'asdf';
      </script>

</head>

will not initialize a global variable, while

 <body>
    <script type='text/javascript'>
       var globalvar = 'asdf';
    </script>
 </body>

will initialize the variable.
Is there a reason for this?

That's simply wrong : the variable you initialize in the head is just as global as the other one.

There is no difference.

But be sure to use the variable after it has been assigned, not before.

Update: The javascript or ECMAscript standard can be found at http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf My answer below may not be fully correct, at least not from the viewpoint of the standard. That is because AFAIK the standard does not specify when the onLoad event should occur or how the global environment is setup when onLoad occurs.


There is no difference to where you define globalvar . However, depending on which webbrowser you use, you may have to wait for the page load event to occur before the variable is available. So a general recommendation is not to execute any javascript code that access global variables before the page load event has occured. To get notified when the page has loaded you can use something like <BODY onLoad="alert('hello world!')"> . The browser will trigger onLoad when the document is finished loading.

//jk

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM