Add Async And Defer Attributes to JavaScript Elements

How to Add Async And Defer Attributes to JavaScript Elements

in Optimization & Best Practice
Google+ LinkedIn

One of the suggestion that you always hear about JavaScript elements is to put them very close to the closing tag of the Web page. The main reason for that is that script elements are fetched and executed immediately when the browser encounter them. In most cases, this will improve website speed considerably.

HTML5 introduces the async script attribute which helps to load scripts asynchronous. But older browsers and any version below Internet Explorer 10 does not support async attribute, therefore you can use defer attribute, that is very similar to the async attribute. Here is example usage of each in HTML.

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

// defer
<script src="scripts.js" defer></script>

So question is which one do you use and what is the main difference between both. Well, this blog post explains the difference between async and defer attributes.

Both async and defer scripts begin to download immediately without pausing the parser and both support an optional onload handler to address the common need to perform initialization which depends on the script. The difference between async and defer centers around when the script is executed. Each async script executes at the first opportunity after it is finished downloading and before the window’s load event. This means it’s possible (and likely) that async scripts are not executed in the order in which they occur in the page. The defer scripts, on the other hand, are guaranteed to be executed in the order they occur in the page. That execution starts after parsing is completely finished, but before the document’s DOMContentLoaded event.

It’s very important to remember not to use the defer attribute on external script files that use the document.write or generate document content. But both, async and defer attributes can be used simultaneously on a script element.

“The defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that only support defer (and not async) to fall back to the defer behavior instead of the synchronous blocking behavior that is the default.”

Here is a code snippet to add the async and defer attributes to all script elements. You can add this snippet to your functions.php file.

// add async and defer to javascripts
function wcs_defer_javascripts ( $url ) {
    if ( FALSE === strpos( $url, '.js' ) ) return $url;
    if ( strpos( $url, 'jquery.js' ) ) return $url;
    return "$url' async='async";
add_filter( 'clean_url', 'wcs_defer_javascripts', 11, 1 );

Share the love

If you like this snippet, share it with others!

13 Replies on "Add Async And Defer Attributes to JavaScript Elements"

  1. Cuong

    What’s myinit() function in your code.

    1. Hey Cuong,
      Good catch. I just fixed the code.
      It did not do anything here, in this particular code snippet.

      Thanks for pointing out. :)

      1. Thai

        How if I apply both async and defer together?

      2. Thai,

        You can use both. No problem. But you also must check what type of browser your visitors use. On one of my site, 95% of visitors are using modern browser, so I only use async.

  2. chetan nada

    wow nice article about async i understand all the things abut this attribute
    thanks for sharing such nice article.

    1. Thank you for stopping by.
      I am glad you like this guide. :)

  3. Mark

    Your PHP script worked. I tried many other versions that only broke the theme and blocked the website from loading (blank page).

    Would be nice to have a script that gives the option to list specific JS scripts as ‘defer’ or async’ to our choosing. That may also increase page speed when it would be better to defer certain scripts rather than async them.


    1. Mark,
      I am glad it worked for you. This is very simple code/function and works all the time.
      We are also using this function on this website too. :)

      Yes, it is possible to selectively use defer and async on scripts. You will need to define few more if conditions in function to check script handler names and add appropriate attribute.

  4. Mark

    Forgot to note:
    I tried all compatible WordPress Plugins that claim to do the same thing, but all of them broke the WordPress theme. It could be the theme itself, which was a Cherry Frame Work theme, which I was not impressed with (but the client wanted it), but whichever the cause of the theme break, your method above worked.

    Also, using Google Page Speed test tool ( ), I saw that a few JS scripts were not modified with the above PHP script. Had to locate the PHP files that controlled the loading of those JS scripts and made the manual modification myself. In particular “header.php”, where I had to add the attribute and value to the HTML script call

    <script src="/js/” async=’async’ type=”text/javascript”>

    Thought I would add this info to help anyone else who had the dragged out struggle with trying to find ways to deal with render blocking scripts.

    In all the PHP method above and a few manual changes, removed all problem scripts that were blocking web page rendering and speed, as per the Google Page Speed test results.

    1. Mark, this function will add async attribute on scripts that are enqueued in WordPress which is the recommended way to add JavaScript scripts in WordPress.

      If there is any JavaScript file added in theme by hardcoding it into theme files then this function will not work on them and you will have to manually edit those links. But that raises some red flag for me because a developer including JavaScript files directly and not enqueue them, does not know what he is doing and I would stay away from such themes and plugins.

      But great suggestions for people who might run into similar problems. Thank you.

  5. Candy

    Thank you for much .wonderful article.
    It really help me alot.

  6. Bican Marian Valeriu

    Which one is better ? async or defer …and what’s the diference ?

    1. If you would read the article then you would know yourself. Also, it depends on how you want to use it and who your target audience is and what type of system they use.

Leave a Reply

Your email address will not be published. Required fields are marked *