Loading JavaScript Asynchronously

BuySellAds and Google Analytics, in an attempt to make the internet faster, recently changed the code snippets they use for serving ads and tracking visitors, respectively, to be non-blocking and asynchronous. This means that the scripts won’t hold up the rendering of your pages while they load. If you reload this page, as an example, the ads to the right may actually appear after the rest of the page has finished loading. It gives the appearance of being a lot faster.

How can you load your own scripts asynchronously? Here’s an example I put together after dissecting Googles’ and BuySellAds’ scripts:

<script id="myscript" type="text/javascript">

(function() {
 var myscript = document.createElement('script');
 myscript.type = 'text/javascript';
 myscript.src = ('http://example.org/myscript.js');
 var s = document.getElementById('myscript');
 s.parentNode.insertBefore(myscript, s);
})();

</script>

What it does is it dynamically assembles and writes out a <script type="text/javascript" src="..." /> DOM element, placing it just before the loader script. You could alter the insertBefore part to append loaded script to the <head> element if you’re so inclined.

You can read further on this technique from these sources:

  • http://www.bloginuityreport.com Sherry

    I stumbled on this site through WP. Great site & great info. Kudos
    You are book marked forever.

  • Joshua

    I noticed this post, made it’s way to the top of Google search for ‘Loading Javascript asynchronously’. Thanks for the quick post and helpful post. (Yes I know this post was almost a year ago. Thanks again).

    • http://www.webmaster-source.com Matt

      I write my posts to last, often. :)

      There had been a lack of easy-to-find information about async JavaScript (and it seems there still is…) so I figured I would get the ball rolling. I’m glad you found it helpful.

  • http://www.patinencomun.com/ skate

    Also may work to load css files asynchronously. I will test…
    Thank you for the idea!
    PD: Testing on http://www.webpagetest.org

  • http://www.1web.ro N Paun

    I noticed the Google script way ago, but never saw somebody else using this method. Thanks!

  • http://collegers.net/forum.php Siva

    Should I use this code for each and individual js file?

    Is it possible to add multiple js file in same block?

  • Vance Three

    That’s great to hear! By making the code snippets for BuySellAds and Google Analytics non-blocking and asynchronous, they have effectively improved the loading speed of websites. Cheers! | drywall finishing cost

  • Olive

    Awesome post! Glad to check this site for this informative content. epoxy garage floor

  • Юрій С

    https://shanovna.com.ua/ – все, що цікавить сучасну жінку