简体   繁体   中英

Javascript in <head> executes before script in <body>

I'm attempting to write a little javascript but have almost no experience in this area.

I've read posts suggesting that <script> blocks inside of <head> are guaranteed to run before those in <body>, but I'm seeing exactly the opposite behaviour. Could someone explain to me why I'm seeing this?

Here is my simple test page:

<html>
  <head>
    <script type="text/javascript">
    var test_msg;
    function initMap() {
      test_msg = "This is a test";
      window.alert('initMap: ' + test_msg);
    }
    </script>
  </head>
  <body onload="initMap()">
    <script type="text/javascript">
      window.alert('blargo: ' + test_msg);
    </script>
  </body>
</html>

When I load this (in either Firefox or IE) I see 2 message boxes: #1: "blargo: undefined", and #2: "initMap: this is a test", suggesting the later script is being executed first.

Thanks for any help,
gs.

Your first script is being executed first... but all it does is create the function and variable.

You're then invoking the function here:

<body onload="initMap()">

....which ensures that the function will not be invoked until all the document resources have loaded.


So the overall order of code execution is:

   // first script
var test_msg;
function initMap() {
   test_msg = "This is a test";
   window.alert('initMap: ' + test_msg);
}


   // second script
window.alert('blargo: ' + test_msg);


   // function call via window.onload
initMap();

Thing is that your function initMap is called when the body is loaded ( body onload='...' ) but the body is only loaded entirely when your last script is loaded and thus executed. You are confusing loading the javascript and executing it.

If you want your function in head block to be executed immediately, just call it below its definition. If the function utilizes some control values, then you need to wrap it in document.ready block.

Ideally in a CMS scenario, the immediately called functions in header will be used for general initialization, those in body should have a wrapper as document.ready to have all controls initialized

<head>
<script> 
function Initialize() { doSomething }  

// Now call this explictly
Initialize();
</script>
</head>
<body>

... body elements

<script> 
$(document).ready(function() { 
     handle body's element as desired using various functions
}
</script>

</body>

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