What is the difference between loading and execution of a file as it pertains to Javascript? Lesson didn’t really touch much on this, and I feel it’s key to understanding the defer
and async
attributes
Hey. It doesn’t have so much to do with the async
keyword, but with defer
, indeed.
If you put your script tag in the head of an html file without the defer
keyword, it is likely that your Javascript is loaded prior to the html content.
So if you have references like document.getElementById('id')
without the DOM content being ready, you’ll get a reference error.
Hi, thanks for replying. What I meant is, what’s the difference between the term ‘loading the file’ and ‘executing the file’. I understand that defer
waits until the DOM is fully parsed
Edit: Also, does that mean async
is pointless if we plan to use the DOM?
Not sure what context you have in mind, but I would say that you load the Javascript in your html head:
<script type="text/javascript" src="path-to-javascript-file.js" defer></script>
And then you execute it in the Javascript file:
class Whatever {
constructor(el){
this._domElement = el;
}
}
const el = document.getElementById('id');
new Whatever(el);
I never used the async keyword in an html head and can’t think of a use case. But according to this article.), it can also be in the head tag instead of the defer keyword:
Note: The
async
attribute is only for external scripts (and should only be used if thesrc
attribute is present).
I only used the async keyword in my Javascript when getting external data from an API, for example:
const data = await fetch(`${url}${query}`, {'headers': headers})
.then(response => {
if (response.status !== 200) { throw new Error("Bad Server Response"); }
return response.json()
});
I see. As for the code in this lesson:
<script id="blue" src="turnBlue.js" async></script>
</head>
<body>
<p class="centered" id="logo">Codecademy</p>
Why does the script change the colour of the text if async
runs the Javascript code before parsing the rest of the HTML?
It does not necessarily run before the DOM content is loaded. In your example, it’s just a p tag. No images, videos etc. So your DOM content is likely to be ready before your JS is.
Ahhh ok got it. Thanks!
Can I get some help with the whole Handlebars stuff?.. I can’t seem to figure it out.