Skip to Content
Codecademy Logo

JavaScript Interactive Websites

Print Cheatsheet

HTML script element src attribute

The src attribute of a <script> element is used to point to the location of a script file.

The file referenced can be local (using a relative path) or hosted elsewhere (using an absolute path).

<!-- Using a relative path --> <script src="./script.js"></script> <!-- Using an absolute path --> <script src=""></script>

HTML script element defer attribute

The defer attribute of a <script> tag is a boolean attribute used to indicate that the script can be loaded but not executed until after the HTML document is fully parsed. It will only work for externally linked scripts (with a src attribute), and will have no effect if it is applied to an inline script.

In the example code block, the <h1> tag will be loaded and parsed before the script is executed due to the defer attribute.

<body> <script src="main.js" defer></script> <h1>Hello</h1> </body>

HTML script tag async attribute

Scripts are loaded synchronously as they appear in an HTML file, before the following HTML is loaded and parsed. The async attribute can be used to load the scripts asynchronously, such that they will load in the background without blocking the HTML parser from continuing.

In the example code block, the script will load asynchronously in the background, without blocking the HTML parser.

<body> <script src="main.js" async></script> <h1>Hello world!</h1> </body>

HTML script element

The HTML <script> element can contain or reference JavaScript code in an HTML file. The <script> element needs both an opening and a closing tag, and JavaScript code can be embedded between the tags.

<script> console.log("Hello world!"); </script>