Chris Martin
Chris Martin

Reputation: 30746

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?

Upvotes: 4

Views: 3545

Answers (2)

Nisarg Shah
Nisarg Shah

Reputation: 14561

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.

Upvotes: 3

CertainPerformance
CertainPerformance

Reputation: 371019

Yes, see MDN: : The Script element

Scripts without async or defer attributes, as well as inline scripts, are fetched and executed immediately, before the browser continues to parse the page.

The document will not be fully parsed until it gets to the end, and when it encounters a script tag, it will stop parsing and wait for the script to download (if necessary) and run before continuing.

This is pretty bad though - you don't want to delay the page from being parsed and rendered. It would be better to give your script tag a defer (or async) attribute - that way, it will automatically run once parsing is finished without blocking, and without requiring you to wrap your whole script in a DOMContentLoaded listener.

Upvotes: 0

Related Questions