This page looks best with JavaScript enabled

Load external scripts asynchronously

 ·   ·  ☕ 2 min read

Load external scripts asynchronously in Javascript.

We have seen about loading functions asynchronously in Javascript. But, what about the scripts that you load from other files, CDNs or other external sources

You can do a simple async to load scripts without impacting the loading speed as perceived by the user.

1
<script src="loadMe.js" async></script>

This will load loadMe in the background without impacting any elements displayed on the page.

Alternatively, you can also do a defer.

1
<script src="loadMe.js" defer></script>

This will make it explicit to the engine to start loading loadMe only after the page has been completely loaded.

Use defer or async to perception of the page load speeds in your application.

Also, note that the async load will be in the same order that you provide. This can be mighty useful to manage dependencies.

1
2
<script src="loadMe1.js" defer></script>
<script src="loadMe2.js" defer></script>

Obviously, do not use async to load scripts that manage your page’s core functions. For example, loading Vue asynchronously will throw an error if you have rest of the page expecting Vue features to be available.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<!-- error -->
<!DOCTYPE html>
<html>
  <head>
    <script src="https://unpkg.com/vue" defer></script>
  </head>
  <body>
    <script type="text/javascript">
      var app = new Vue({
        el: "#app"
      });
    </script>
  </body>
</html>
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things