Hyunjik Bae
Hyunjik Bae

Reputation: 2949

JavaScript code running order in HTML page

In a web page, when JavaScript starts to run? For example,

HTML section 1
Javascript section 1
Event handler routine 1
HTML section 2
Javascript section 2
Event handler routune 2

Is this running order correct?

  1. Web page load complete
  2. Image file load complete
  3. Javascript section 1 starts and finishes execution
  4. Javascript section 2 starts and finishes execution
  5. Event handler routine starts on event

Will no event handler routine run before JavaScript section 2 is finished?

Upvotes: 3

Views: 420

Answers (2)

Aditya Bhave
Aditya Bhave

Reputation: 1028

In a web page, when JavaScript starts to run?

Well, it depends on where javascript is written. It is executed as soon as it is downloaded (from a file) or as soon as it is read by browser if inline in html.

If your javascript is inside some event like window.onload or $(document).load(...) then it will be executed after page is rendered.

Event handlers are executed as a response to an event. So, there is no specific order here. As soon as the event occurs, event handler is fired.

Consider following example.

<html>
<body>
  <h1 id="first">
    First
  </h1>

  <script type="text/javascript" lazyload>
    var first = document.getElementById('first'); // logs element
    var second = document.getElementById('second'); //logs null

    console.log(first);
    console.log(second);
  </script>

  <h1 id="second">
    Second
  </h1>

  <script type="text/javascript" lazyload>
    var first = document.getElementById('first'); //logs element
    var second = document.getElementById('second'); //logs element

    console.log(first);
    console.log(second);
  </script>
</body>
</html>

Above example demonstrates that #first was rendered before js block 1 executed but #second was not rendered by this time.

Upvotes: 1

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92697

No, js is executed in place where it is defined - so in below example you cannot use div defined in section 2 html (id='sec2') in js script defined before it (you will see error). However if you use html-inline event handlers then you can use js function defined after html element definition

<body>

<div id='sec1' onclick="show('sec1')">HTML section 1 (click me)</div>

<script>
  console.log('Javascript section 1');
  console.log('sec1 html:', sec1);
  console.log('sec2 html:', sec2);
</script>

<div id='sec2' onclick="show('sec2')"> HTML section 2 (click me)</div>

<script>
  console.log('Javascript section 2');
  console.log('sec1 html:', sec1);
  console.log('sec2 html:', sec2);

  function show(msg) { alert(msg) };
</script>

</body>

Upvotes: 1

Related Questions