In web programming, JavaScript brings interactiveness and dynamic behaviour to your web pages. While HTML and CSS take care of the structure and aesthetics of the pages, they will be merely usable without JavaScript doing its job in the background.
You can include JavaScript code in the HTML file in several ways. The most standard approach is to keep the JavaScript code in a separate file with the .js
extension and then load that file into the HTML file for the script to download and execute.
In this article, you will learn the most efficient way of loading a JavaScript file into HTML to improve the application's page loading speed. We will deep dive into visually understanding two special HTML attributes, async
and defer
, and how they help improve page loading.
If you like to learn from video content as well, this article is also available as a video tutorial here: 🙂
How Do We Load Scripts into HTML?
Let's first understand the basics of loading JavaScript code from an external file. Assume we have a file called some-script.js
(note the file extension. It's .js which stands for JavaScript) with all the JavaScript code.
You need to use the <script>
tag to load and execute this code. The src
attribute of the