Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
CSS-Tricks
Search

Async Attribute and Scripts At The Bottom

Chris Coyier on

Get affordable and hassle-free WordPress hosting plans with Cloudways —start your free trial today.

A reader recently wrote in and (essentially) asked me:

Is there any reason to use theasync attribute when thescript is already at the bottom of the page?

I’m not a master at this stuff, but this is how I understand it…

What he was talking about was this:

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

We’vecovered this before a bit. It’s extra-interesting to re-visit now though, becausetheasync attribute is now reallythe only recommended way to be doing async scripts.

So,is there any reason to use theasync attribute when thescript is already at the bottom of the page?

Short Answer

No.

Longer Answer

What you are trying to prevent with theasync attribute is parser blocking. If you use theasync attribute, you are saying: I don’t want the browser to stop what it’s doing while it’s downloading this script. I know that this script doesn’t really depend on anything being ready in the DOM when it runs and it also doesn’t need to be run in any particular order.

If you load the script at the bottom of the page, the parser is effectively done already, so blocking it isn’t a big deal. You’re essentially alreadydeferring the script, which is kinda like a more hardcore async.See comparison.

It might even be a little dangerous.

If you were just operating under the assumption that async = good, you might do something like:

  <script async src="/js/libs.js"></script>  <script async src="/js/page.js"></script></body>

That could be bad news, because chances are “libs.js” has dependencies for “page.js”, but now there is no guarantee the order in which they run (bad).

It’s mostly third-party thing.

Third-party scripts are the big use-case for async scripts. They (the third-parties) can’t control where you put that script on your page, so they are typically designed to work no matter when/where they load anyway. You also can’t control third-parties (that’s what a third-party is, Wayne) so making darn sure they don’t slow your site down is ideal.

Is there any other use-cases?

I guess if you really wanted to get the download started on one of your own scripts right away, and it didn’t matter when it ran, you could put it in the<head> and async it.

I might be kinda wrong.

I tend to screw up these JavaScript advice posts, so if I did, let’s talk about it in the comments and I’ll make sure the content of this post reflects the best information.

Psst! Create a DigitalOcean account and get$200 in free credit for cloud-based hosting and services.

Comments

  1. alexander farkas

    There is still a usecase to use async, although it was put at the bottom. Any script added sync inside the document blocks the domcontentloaded (ready) event, which is often used to initialize UI widgets/components.

    But you are absolutley right. The most important use case for async nowadays would be third party code, which must be loaded async or better using friendly iframe technique. Unfortunaltey this is often impossible, because of bad written scripts.

  2. Barış Ünver

    I like the short answer, it’s cleaner.

  3. Chris

    According to a comment by the author in the article linked @ igvita.com there is still a benefit:

    Q: Does async attribute make a difference if the script tag is at the extreme bottom of the page? Because by that time the DOM would be fully constructed (assuming CSSOM is also constructed) and there is nothing to block.

    A: Yes, it does, script[async] scripts are discoverable by the preloader, which means that if the parser is blocked earlier in the page (which is highly likely), then the script can still be discovered and network request can be dispatched before the parser reaches the actual script… For an example, compare the first and third screenshots in post above.

    Thanks for this post, I wouldn’t have learned these tidbits about async otherwise!

    See:https://www.igvita.com/2014/05/20/script-injected-async-scripts-considered-harmful/#comment-1398899164

    • Chris Coyier

      Does that mean the preloader can’t find scripts that don’t have the async attribute? That seems weird. Just wondering here, I’ll have to dig into that conversation to find out more.

    • T.J. Crowder

      @ Chris Coyier: Both are discoverable by the preload scanner. But if you have (say) two scripts that aren’t interdependent, marking each with the async flag lets the browser run them in either order, and so if (say) the first one is being being slow to download, the browser is free to go ahead and run the second one before the first one finishes downloading and gets run. If you leave off the async, the second still has to wait for the first. So it still has a useful purpose, even when the scripts are right at the end of the HTML.

    • Chad von Nau

      @ChrisCoyier @Chris The quote is about using the async attribute vs using script injection. It doesn’t address whether or not to use the async attribute on a script tag.

      My understanding of the async attribute is well summarized by @T.J.Crowder. The async attribute is beneficial if you know what you’re doing, but is not a good default for bottom-loaded script tags, as Chris concluded in the article.

  4. Jonathan

    While I agree that you shouldn’t use it because it doesn’t guarantee the order of execution… By using the async attribute, it actually executes the script twice as normal script tag. Injecting via the script tag into the dom takes 0.1sec longer on average but I still think that’s the best solution.

  5. علی‍رضا معظمی

    Is there any reason to use theasync attribute when thescript is already at the bottom of the page?
    i say: No, bu sometime Yes!

    when bottomscript is independent from each other, we can useasync so the latency of loading first script does not affect second one.

  6. Chris Smith

    Further question. If you were loading, say, 10 scripts at the bottom of your page and there were no dependencies, would loading them all async help them to load faster, all in parallel, rather than maybe 6 requests then a further 4?

  7. josh

    I have a die-hard backend dev friend who swears that putting scripts at the bottom of the page is bad practice and gets really annoyed when he is searching through pages trying to find the scripts and then finds them below. Is it really preferable to place them before the end of the body or is it mostly a convenience thing?

    • CBroe

      Does he have any reasoning as towhy that would be bad practice – I mean, apart from that is just “annoys” him that it takes him a little longer to find them …?

  8. Kellen Green

    Should anyone want to dive a little deeper. This is my go to article for JS loading, I’ve found it very informative in the past.
    http://www.html5rocks.com/en/tutorials/speed/script-loading/

  9. Sim

    josh:
    Its not for convenience, its for performance. Adding the scripts before the body will increase the rendering time. With some exception, some analytic script prefer developer to put the script on the head, this is so that they can track it as soon as the page is being called.

  10. Tim Wright

    What about just using async with 1 concatenated script instead of breaking them all apart, worrying about execution order and potentially burning http requests? Runningcat *.js &gt; app.min.js on the command line over your JS file will concatenate everything.

    • Chris Coyier

      Concatenation is another issue I think. It’s important. From the perspective of this article, it should be assumed you’ve already done as much intelligent concatenation as possible. Just because a page loads two scripts doesn’t mean they are dropping the ball on concatenation. It might make perfect sense to have aglobal.js that loads on all pages (and thus leverages caching) andsubpage.js which loads only on some pages, but depends on stuff from global.

    • T.J. Crowder

      @ Chris Coyier: Bang on. Or you’ve made the business decision to download standard things from a free CDN and your own stuff locally (and dealt with handling what happens if those are in a chaotic order).

      None of this stuff is dogma. It’s pragmatic choices, intelligently made.

      Or at least, you know, that’s what we’re shooting for anyway… ;-)

  11. joan
     AsyncLoader.Ready(function () {     AsyncLoader.Load(["jQuery", "extensions"], function () {         // Application code here.     }); });

    What about asynchronously loading scripts like this?

    • joan

      Hmm, I wanted to insert HTML code…
      <script src=”/js/AsyncLoader.js”></script>
      <script>
      AsyncLoader.Ready(function () {
      AsyncLoader.Load([“jQuery”, “extensions”], function () {
      // Application code here.
      });
      });
      </script>

  12. Tom

    http://www.dustindiaz.com/scriptjs

    async loading with dependency management KAPOW.

    A dependency attribute would be better but as it doesn’t exist this is v useful.

  13. Santosh

    Thanks for your clarification. Recently I have been facing the async issue on my project. I prefer loading the script at the footer. But is there any disadvantage of placing the script at the bottom of page ? Even one ?

This comment thread is closed. If you have important information to share, pleasecontact us.

[8]ページ先頭

©2009-2025 Movatter.jp