Script Loading
Overview
To use JavaScript in an HTML file, we need to load it using the <script> tag.
Historically, developers placed scripts at the very bottom of the <body> so that the HTML could load first. Today, we use the defer or async attributes in the <head> to load scripts much more efficiently without blocking the page from rendering.
Syntax
Using defer is the modern best practice. It ensures your script doesn't slow down the visual loading of the page, but guarantees the DOM is ready when your script runs.
<!DOCTYPE html>
<html>
<head>
<!-- 'defer' downloads the script in the background, but waits for HTML to parse before running it -->
<script src="app.js" defer></script>
</head>
<body>
<h1>My Website</h1>
</body>
</html>While possible, writing JS directly in HTML (inline) is considered bad practice for large projects because it mixes logic with structure.
<script>
console.log("This JS is written directly inside the HTML file.");
</script>Common Pitfalls
- Forgetting to link the
.jsfile and wondering why the code isn't working. - Putting
<script src='app.js'></script>in the<head>withoutdefer. The browser will pause loading the HTML until the script finishes downloading, causing a white screen delay!
Interview Questions
Both download the script in the background. However, 'async' executes the script immediately once downloaded (pausing HTML parsing), and order is not guaranteed. 'defer' waits until the entire HTML is parsed before executing, and guarantees scripts run in the order they appear.
Real-World Example
Google Analytics provides a script that you should load using async because it doesn't need to wait for your DOM to be ready, and it shouldn't block your page from loading.
<!-- Google Analytics is often loaded with async -->
<script async src="https://www.google-analytics.com/analytics.js"></script>Check Your Knowledge
Test your understanding of Script Loading with these quick questions.