Kula.blog

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 about defer! Read on to learn more.

Advantages:

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:

In old browsers:

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


← Home