If you've been coding in JavaScript for long enough, you'll know there are various ways to include a script into your HTML document.
Unfortunately, due to the age of JavaScript, there are many techniques to include external files on the web - many of which are outdated.
So, what's the preferred way to do this?
The Defer Attribute 💪
Let me introduce you to the defer
attribute. This is valid on the HTML <script>
tag, and is a perfect solution for most scenarios.
When a <script>
tag is placed in the <head>
and has the defer
attribute, the external script will be loaded asynchronously with the rest of the page and will only execute after the document has been parsed.
There are 3 primary benefits of this:
- page loads quicker ⚡
- better semantics compared to putting a
<script>
at the end of<body>
- most importantly, preventing errors ❗
Which errors am I talking about?
The ones where elements cannot be found (or are null
).
We've all done it before - tried to select an HTML element before the document has been parsed, resulting in error messages along the lines of "cannot access X of null
".
Solutions for this in the past involved using the onload
event or even better, the DOMContentLoaded
event. Now, we have the defer
attribute.
Here's an example of it's usage:
<!DOCTYPE html>
<html>
<head>
<title>Website Title</title>
<script src="js/main.js" defer></script>
</head>
</html>
// src/main.js
// Only executes once the DOM has been parsed - no errors! 😏
const myInput = document.getElementById("myInput");
I hope the defer
attribute serves you well 💪
Enrol Now 👉 JavaScript DOM Crash Course
You can find a complete course on the JavaScript DOM which goes over some of the topics covered in this post at the link below 👇
https://www.udemy.com/course/the-ultimate-javascript-dom-crash-course/?referralCode=DC343E5C8ED163F337E1
Enjoy!
Top comments (1)
thank you, it's helpful.