skip to Main Content

I am working on updating a Google Sign-In component. The Google doc says to include the following in my html file:

<script src="https://accounts.google.com/gsi/client" async defer></script>

Here is the doc Google Doc.

My understanding of the async and defer attributes is that they load the script in a different order, and therefor can not both be applied at once. Here is a SO article for reference SO article.

So am I misunderstanding something or why is the Google Document telling me to use both tags?

4

Answers


  1. Yes, they’re mutually exclusive.

    async is related to downloading of the script. It means that the HTML parsing should not be blocked while downloading the script.

    defer is related to execution of the script. It means that the execution should be deferred till all the HTML parsing is completed.

    But as this answer noted, if you specify both, defer is ignored.

    You can still specify both though to support old browsers that don’t support async.

    Login or Signup to reply.
  2. Yes they are mutually exclusive. When the async attribute is present (and supported), the defer one is discarded.

    If you look at the specs, (step 33, temp link).

    1. If el‘s type is "classic" and el has a src attribute, or el‘s type is "module":

      1. Assert: el‘s result is "uninitialized".

      2. If el has an async attribute or el‘s force async is true:

        1. Let scripts be el‘s preparation-time document’s set of scripts that will execute as soon as possible.

        2. Append el to scripts.

        3. Set el‘s steps to run when the result is ready to the following:

          1. Execute the script element el.

          2. Remove el from scripts.

      3. Otherwise, […]
        […]
      4. Otherwise, if el has a defer attribute or el‘s type is "module":

    From this we can see that when the async attribute is set, the time of the script’s execution is already defined, and that the defer attribute is discarded through the Otherwise logic clause.

    You can still let both to fallback on the defer behavior when async isn’t supported though.

    Login or Signup to reply.
  3. defer is ignored when async specified, and async always have higher priority.
    but old browsers did not have support for async and it’s rather a new option. so when you write

    <script src="https://accounts.google.com/gsi/client" async defer></script>
    

    it means browser should use async method to load script unless it does not support it, if so it can use defer instead.

    Login or Signup to reply.
  4. If you use both async and defer, then defer will take precedence and the script run when the page load is complete, meaning they are not mutually exclusive.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search