-2

I have a script inserted on the head of the page like this

<head>
   ... load jQuery ....
   <script>var bbody = $('body');</script>
</head>
<body>
  ....

   <script>console.log(bbody);</script>
   <script>console.log($('body'));</script>
</body>

And always the result of the console.log in the first sentence it's undefined, but the second it's the correct object, So my question is:

  1. ¿Always the code on the <script> is executed at the moment on the interpreter read the code inside in?
  • 1
    b/c that point of time body was not available . – Jai Apr 19 '17 at 12:15
  • Yes, it synchronous (Unless you load a js file with `defer`/`async` - Then the browser will render the content and only then load the script, when you use `defer` you can trust that the scripts will execute in the same order) – Alon Eitan Apr 19 '17 at 12:15
  • @AndreiGheorghiu something this basic ... you know it has to have been asked many many times though – charlietfl Apr 19 '17 at 12:27

2 Answers2

2

Its hierarchical. The <body> is still not in picture, for the first <script> tag. So, undefined.

You can use $(document).ready to define your bbody to make sure the dom loads first.

$(document).ready(function(){
  var bbody = $('body');
});
nikamanish
  • 642
  • 4
  • 17
1

Wrap your var bbody = $('body'); in a $(document).ready to make sure that the body tag exists when you want to load it.

$(document).ready(function(){
    var bbody = $('body');
});
Mazz
  • 1,739
  • 21
  • 37