Learn JS. How to run JavaScript in the browser
Over the years there were multiple recommended ways of loading JavaScript. What's the best way to work with JS now? Just use deferred <script>
tag in the <head>
of our page:
<head>
<script
defer
src="/your_js_file_name.js">
</script>
</head>
Wait! Wasn't it a bad practice to place scripts in the
head
? Yes, it was. It still is if you forget aboutdefer
! Read on to learn more.
Advantages:
- It will work everywhere
- Will load asynchronously (the browser will wait for it to load and execute it before firing
DocumentContentLoaded
because of thedefer
) - 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
What about new JavaScript Modules? #
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!
<head>
<script
type="module"
src="/your_js_modules_file_name.js">
</script>
<head>
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? #
There is only one problem with modules. Do you care about IE 11 or the Baidu browser? Please check current support at Can I use JavaScript modules via script tag.
You can use babel to compile your JavaScript to the older format and load it as in the first example. You will work with modules during development but will provide the old form to all browsers. Or you can create separate files for newer and older browsers as in the example below!
<head>
<!-- for new browsers -->
<script
type="module"
src="/your_js_modules_file_name.js">
</script>
<!-- for old browsers -->
<script
nomodule
defer
src="/your_js_file_name.js">
</script>
<head>
In new browsers:
type="module"
will just runnomodule
attribute will tell a new browser to ignore this script
In old browsers:
type="module"
—module
won't be recognized as a valid type and the whole script will be ignorednomodule
attribute will be ignored, but the script by default hastype="application/javascript"
so it will be executed.
The trick is to make sure JavaScript modules won't be executed in old browsers (by setting 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 nomodule
attribute.
Update 2019-08-23 #
I can recommend an article about Using Native JavaScript Modules in Production Today
Want to learn more?
Sign up to get a digest of my articles and interesting links via email every month.