Asset loading optimization – async, defer, preconnect, preload, and prefetch
When using script
to load and execute JavaScript, there are HTML attributes of script
we can use to control the loading and execution.
We can rely on the difference between external scripts and inline scripts; we can also use the async
, defer
, and type="module"
attributes.
We’ll start by defining external and inline scripts, then the async
and defer
attributes. Finally, we’ll look at classic and module scripts via the type="module"
attribute.
External scripts use the src
attribute to point to a separate JavaScript file; for example, what follows is an external script that will load and evaluate ./script.js
when it’s encountered:
<script src="./script.js"></script>
Contrast this with inline scripts, where there is no src
attribute; instead, the JavaScript code is in the script
tag contents:
<script> console...