4

I have the following test to see whether the defer attribute defers execution of script block. There are 2 script blocks. 1st one with the defer attribute and 2nd one with out. If I understand correctly, the attribute forces the browser to execute the block when all html parsing has been completed (including the other script block).

But looking at the console, I always the 'from deferred' first. Why is that? Does defer not work on the local script blocks?

<html>
<body>
   ...

  <script type="text/javascript" defer>
    console.log('from deferred');
  </script>

  <script type="text/javascript">
    console.log('from regular');
  </script>

</body>
</html>
AngryHacker
  • 59,598
  • 102
  • 325
  • 594

1 Answers1

21

defer only works on external scripts:

This attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect.

To achieve a similar effect for dynamically inserted scripts use async=false instead. Scripts with the defer attribute will execute in the order in which they appear in the document.

Also,

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

Because local scripts are executed before the page finishes parsing, defer will not apply. defer gets applied after parsing, but before DomContentLoaded.

Community
  • 1
  • 1
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71