<script> tag in the
<head> of our page:
Wait! Wasn't it a bad practice to place scripts in the
head? Yes, it was. It still is if you forget about
defer! Read on to learn more.
- It will work everywhere
- Will load asynchronously (the browser will wait for it to load and execute it before firing
DocumentContentLoadedbecause of the
- Deferred scripts are executed in their order in HTML
- You can add it everywhere - it's even better if it's in the
<head>as the browser will start downloading it as soon as possible
You can use modules by just adding
type="module" to your script. It will just work! No need for fancy tools like babel or webpack. Scripts with
module don't need to add
defer attribute as modules are deferred automatically!
What's the catch? Why not use modules instead of the
defer? The problem is support in older browsers. If you don't care about them, then you're free to use them, e.g., new internal tools.
Old browsers? #
<!-- for new browsers -->
<!-- for old browsers -->
In new browsers:
type="module"will just run
nomoduleattribute will tell a new browser to ignore this script
In old browsers:
modulewon't be recognized as a valid type and the whole script will be ignored
nomoduleattribute will be ignored, but the script by default has
type="module"). And that there is a way to ignore fallback scripts in new browsers — so that you don't load and execute the same things twice by setting the
Update 2019-08-23 #
Want to learn more?
Sign up to get a digest of my articles and interesting links via email every month.