javascriptdomdomcontentloaded

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?


Solution

  • 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.