Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do scripts in the document head always execute before DOMContentLoaded fires?

In the following document,

<!doctype html>
<html>
  <head>
    <script language="javascript" src="example.js"></script>
  </head>
  <body>
  </body>
</html>

Where example.js is:

document.addEventListener('DOMContentLoaded', function () {
    console.log('hello');
});

Is the log statement guaranteed to be executed?

like image 576
Chris Martin Avatar asked Oct 18 '25 13:10

Chris Martin


1 Answers

According to MDN,

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

Note: Synchronous JavaScript pauses parsing of the DOM.

In your case, the way you are referencing the external Javascript file, it is treated as synchronous, i.e. it will be fetched and loaded before the elements after that will be parsed.

So, answer is, yes, it will always execute - as long as the external JS file is available to the browser.


If you had indicated that browser should attempt to download the script asynchronously (by setting async attribute to true), then the event may or may not trigger the callback you register.

like image 84
Nisarg Shah Avatar answered Oct 21 '25 03:10

Nisarg Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!