简体   繁体   中英

how and where to import and place script tag ? async vs defer

How and where can we import <script> tag inside our HTML and what's the deference between async and defer as a property of <script> .

When a script tag executes, everything above it in the DOM is available (but not everything below).

<html>
  <head>
    <script>
      // document.head is available
      // document.body is not!
    </script>
  </head>
  <body>
    <script>
      // document.head is available
      // document.body is available
    </script>
  </body>
</html>

You can think of the HTML parser as traveling through the document tag by tag, executing any JavaScript as it approaches it. This means DOM nodes are available to your JavaScript (through querySelectorAll , jQuery, etc.) only if their opening tag appears earlier in the document that your script tag.

async and defer

HTML5 has added a couple tools for controlling when scripts execute.

async means “ execute this whenever ”. More specifically that means: I don't care if you execute this after the whole page has loaded, and every other script has executed. It's very useful for analytics tracking codes, for example, where no other code on the page depends on their execution. Defining a variable or function in async code which the page needs is bad news, as you have no way of knowing when the async code will actually run.

defer means “ wait for the parser to finish to execute this ”. It's roughly equivalent to binding your script to the DOMContentLoaded event, or using jQuery.ready. When the code does run, everything in the DOM will be available for you to use. Unlike async , defer'd code will run in the order it appears in the HTML of the page, it is just deferred until after the HTML is fully parsed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM