Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script defer doesn't seem to work as expected [duplicate]

Tags:

javascript

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>
like image 361
AngryHacker Avatar asked Aug 25 '26 00:08

AngryHacker


1 Answers

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.

like image 128
Obsidian Age Avatar answered Aug 26 '26 16:08

Obsidian Age



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!