Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
115 views
in Technique[技术] by (71.8m points)

javascript - Gatsby setHeadComponents setting async tag

I am rendering a 3rd party script tag using Gatsby's onRenderBody and setHeadComponents API in gatsby-ssr.js.

export const onRenderBody = ({ setHeadComponents }) => {
  setHeadComponents([
    <script
      type="text/javascript"
      async
      key="1"
      src="//www.myscripturl.com/analytics.js"
    />,
  ])
}

However, the HTML that is output sets the async tag as async="".

<script type="text/javascript" async="" src="//www.myscripturl.com/analytics.js"></script>

It's not clear to me if this is allowing async loading of the script or not. Typically, I'd expect the script to output as:

<script type="text/javascript" async src="//www.myscripturl.com/analytics.js"></script>
question from:https://stackoverflow.com/questions/65862462/gatsby-setheadcomponents-setting-async-tag

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the documentation:

For classic scripts, if the async attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available.

For module scripts, if the async attribute is present then the scripts and all their dependencies will be executed in the defer queue, therefore they will get fetched in parallel to parsing and evaluated as soon as they are available.

So, async="", async=true, or async=false will be parsed exactly in the same way because the attribute, whenever it's present, will be evaluated as async either way.

It's not clear to me if this is allowing async loading of the script or not. Typically,

Yes, it will be loaded asynchronously.

You can use a more semantic if you want way using a true value but will have no effect on the final result because the async attribute if it's present, will load the script asynchronously, no matter the value of the attribute.

export const onRenderBody = ({ setHeadComponents }) => {
  setHeadComponents([
    <script
      type="text/javascript"
      async=true
      key="1"
      src="//www.myscripturl.com/analytics.js"
    />,
  ])
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...