0

This is my script.js

document.addEventListener("DOMContentLoaded", function() {
  // this function runs when the DOM is ready, i.e. when the document has been parsed
  var elem = document.getElementById("output");
  elem.innerHTML = 123;
});
<h1>Hello!</h1>
<div id="output">11</div>

When I load index.html in the browser, I don't see a 123 displayed. Why so ?

Original HTML

<!DOCTYPE html>
<html>
<head>
    <title>My page</title>
    <script async type="text/javascript" src="script.js"></script>
</head>
<body>
    <h1>Hello!</h1>
    <div id="output">11</div>
</body>
</html>
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
Ankur Agarwal
  • 23,692
  • 41
  • 137
  • 208

1 Answers1

2

On your post revision history, you previously had <script async type="text/javascript" src="script.js">

async instructs the browser that it can run independently. This means it can also run after DOMContentLoaded has fired. Removed asyncand the event will reliably fire.

Async-loaded scripts with DOMContentLoaded or load event handlers not being called?

enter image description here

Matt Lo
  • 5,442
  • 1
  • 21
  • 21
  • Yes, I changed to "defer" and it started working fine. "async" means downloaded while first render is happening and execute as soon as download is complete. "defer" means download while first render is happening and execute after first render is complete. My script was executing soon after download which was before the first render was complete. Correct ? – Ankur Agarwal Sep 03 '17 at 02:12
  • 1
    Correct. To simplify: `defer` is still blocked by the HTML parser. `async` doesn't care and is independent. – Matt Lo Sep 03 '17 at 02:16