Analysis of delayed execution of js

  • 2020-03-30 03:27:19
  • OfStack

Look at this code:


<body>
  <script src="deffer.js"></script>
  content
 </body>

The content of deffer.js is:


alert(1)

This leaves the page blank until the alert window is closed. Because the alert window prevents the page from being rendered.

To avoid this problem, the deffer and async attributes are defined in the HTML specification. The specific definitions of these two attributes are not discussed here, but they are used to tell the browser that the content of the script should be executed after the page is rendered, so that the page is rendered by the time the script is executed.


<body>
  <script deffer async src="deffer.js"></script>
  content
 </body>

Note that for multiple scripts with deffer or async, the order in which they are executed is independent of the order in which they appear on the page. Even though the HTML specification defines that deffer scripts should be executed in order, browsers don't always follow this convention.


Related articles: