This commit is contained in:
Ilya Kantor 2019-08-05 00:57:55 +03:00
parent 6d1fa5de73
commit d63c27bcc6
7 changed files with 108 additions and 83 deletions

View file

@ -1,8 +1,7 @@
# Modules, introduction
As our application grows bigger, we want to split it into multiple files, so called 'modules'.
A module usually contains a class or a library of useful functions.
As our application grows bigger, we want to split it into multiple files, so called "modules". A module usually contains a class or a library of functions.
For a long time, JavaScript existed without a language-level module syntax. That wasn't a problem, because initially scripts were small and simple, so there was no need.
@ -14,13 +13,15 @@ For instance:
- [CommonJS](http://wiki.commonjs.org/wiki/Modules/1.1) -- the module system created for Node.js server.
- [UMD](https://github.com/umdjs/umd) -- one more module system, suggested as a universal one, compatible with AMD and CommonJS.
Now all these slowly become a part of history, but we still can find them in old scripts. The language-level module system appeared in the standard in 2015, gradually evolved since then, and is now supported by all major browsers and in Node.js.
Now all these slowly become a part of history, but we still can find them in old scripts.
The language-level module system appeared in the standard in 2015, gradually evolved since then, and is now supported by all major browsers and in Node.js. So we'll study it from now on.
## What is a module?
A module is just a file, a single script, as simple as that.
A module is just a file. One script is one module.
There are directives `export` and `import` to interchange functionality between modules, call functions of one module from another one:
Modules can load each other and use special directives `export` and `import` to interchange functionality, call functions of one module from another one:
- `export` keyword labels variables and functions that should be accessible from outside the current module.
- `import` allows to import functionality from other modules.
@ -44,7 +45,9 @@ alert(sayHi); // function...
sayHi('John'); // Hello, John!
```
In this tutorial we concentrate on the language itself, but we use browser as the demo environment, so let's see how to use modules in the browser.
The `import` directive loads the module by path `./sayHi.js` relative the current file and assigns exported function `sayHi` to the corresponding variable.
Let's run the example in-browser.
As modules support special keywords and features, we must tell the browser that a script should be treated as module, by using the attribute `<script type="module">`.
@ -52,7 +55,7 @@ Like this:
[codetabs src="say" height="140" current="index.html"]
The browser automatically fetches and evaluates imported modules, and then runs the script.
The browser automatically fetches and evaluates the imported module (and its imports if needed), and then runs the script.
## Core module features
@ -70,8 +73,6 @@ Modules always `use strict`, by default. E.g. assigning to an undeclared variabl
</script>
```
Here we can see it in the browser, but the same is true for any module.
### Module-level scope
Each module has its own top-level scope. In other words, top-level variables and functions from a module are not seen in other scripts.
@ -82,7 +83,7 @@ In the example below, two scripts are imported, and `hello.js` tries to use `use
Modules are expected to `export` what they want to be accessible from outside and `import` what they need.
So we should import `user.js` directly into `hello.js` instead of `index.html`.
So we should import `user.js` into `hello.js` and get the required functionality from it instead of relying on global variables.
That's the correct variant:
@ -125,10 +126,10 @@ alert("Module is evaluated!");
import `./alert.js`; // Module is evaluated!
// 📁 2.js
import `./alert.js`; // (nothing)
import `./alert.js`; // (shows nothing)
```
In practice, top-level module code is mostly used for initialization. We create data structures, pre-fill them, and if we want something to be reusable -- export it.
In practice, top-level module code is mostly used for initialization, creation of internal data structures, and if we want something to be reusable -- export it.
Now, a more advanced example.
@ -162,7 +163,7 @@ alert(admin.name); // Pete
So, let's reiterate -- the module is executed only once. Exports are generated, and then they are shared between importers, so if something changes the `admin` object, other modules will see that.
Such behavior is great for modules that require configuration. We can set required properties on the first import, and then in further imports it's ready.
Such behavior allows to *configure* modules on first import. We can setup its properties once, and then in further imports it's ready.
For instance, `admin.js` module may provide certain functionality, but expect the credentials to come into the `admin` object from outside:
@ -175,7 +176,7 @@ export function sayHi() {
}
```
Now, in `init.js`, the first script of our app, we set `admin.name`. Then everyone will see it, including calls made from inside `admin.js` itself:
In `init.js`, the first script of our app, we set `admin.name`. Then everyone will see it, including calls made from inside `admin.js` itself:
```js
// 📁 init.js
@ -183,6 +184,8 @@ import {admin} from './admin.js';
admin.name = "Pete";
```
Another module can also see `admin.name`:
```js
// 📁 other.js
import {admin, sayHi} from './admin.js';
@ -204,11 +207,13 @@ Its content depends on the environment. In the browser, it contains the url of t
</script>
```
### Top-level "this" is undefined
### In a module, "this" is undefined
That's kind of a minor feature, but for completeness we should mention it.
In a module, top-level `this` is undefined, as opposed to a global object in non-module scripts:
In a module, top-level `this` is undefined.
Compare it to non-module scripts, where `this` is a global object:
```html run height=0
<script>
@ -224,14 +229,14 @@ In a module, top-level `this` is undefined, as opposed to a global object in non
There are also several browser-specific differences of scripts with `type="module"` compared to regular ones.
You may want skip those for now if you're reading for the first time, or if you don't use JavaScript in a browser.
You may want skip this section for now if you're reading for the first time, or if you don't use JavaScript in a browser.
### Module scripts are deferred
Module scripts are *always* deferred, same effect as `defer` attribute (described in the chapter [](info:script-async-defer)), for both external and inline scripts.
In other words:
- external module scripts `<script type="module" src="...">` don't block HTML processing, they load in parallel with other resources.
- downloading of external module scripts `<script type="module" src="...">` doesn't block HTML processing, they load in parallel with other resources.
- module scripts wait until the HTML document is fully ready (even if they are tiny and load faster than HTML), and then run.
- relative order of scripts is maintained: scripts that go first in the document, execute first.
@ -263,11 +268,13 @@ Please note: the second script actually works before the first! So we'll see `un
That's because modules are deferred, so way wait for the document to be processed. The regular scripts runs immediately, so we saw its output first.
When using modules, we should be aware that HTML-page shows up as it loads, and JavaScript modules run after that, so the user may see the page before the JavaScript application is ready. Some functionality may not work yet. We should put transparent overlays or "loading indicators", or otherwise ensure that the visitor won't be confused by that.
When using modules, we should be aware that HTML-page shows up as it loads, and JavaScript modules run after that, so the user may see the page before the JavaScript application is ready. Some functionality may not work yet. We should put "loading indicators", or otherwise ensure that the visitor won't be confused by that.
### Async works on inline scripts
Async attribute `<script async type="module">` is allowed on both inline and external scripts. Async scripts run immediately when imported modules are processed, independently of other scripts or the HTML document.
For non-module scripts, `async` attribute only works on external scripts. Async scripts run immediately when ready, independently of other scripts or the HTML document.
For module scripts, it works on any scripts.
For example, the script below has `async`, so it doesn't wait for anyone.
@ -287,7 +294,7 @@ That's good for functionality that doesn't depend on anything, like counters, ad
### External scripts
There are two notable differences of external module scripts:
External scripts that have `type="module"` are different in two aspects:
1. External scripts with same `src` run only once:
```html
@ -296,7 +303,7 @@ There are two notable differences of external module scripts:
<script type="module" src="my.js"></script>
```
2. External scripts that are fetched from another origin (e.g. another site) require [CORS](mdn:Web/HTTP/CORS) headers, as described in the chapter <info:fetch-crossorigin>. In other words, if a module script is fetched from another origin, the remote server must supply a header `Access-Control-Allow-Origin: *` (may use site domain instead of `*`) to indicate that the fetch is allowed.
2. External scripts that are fetched from another origin (e.g. another site) require [CORS](mdn:Web/HTTP/CORS) headers, as described in the chapter <info:fetch-crossorigin>. In other words, if a module script is fetched from another origin, the remote server must supply a header `Access-Control-Allow-Origin` allowing the fetch.
```html
<!-- another-site.com must supply Access-Control-Allow-Origin -->
<!-- otherwise, the script won't execute -->
@ -332,13 +339,6 @@ Old browsers do not understand `type="module"`. Scripts of the unknown type are
</script>
```
If we use bundle tools, then as scripts are bundled together into a single file (or few files), `import/export` statements inside those scripts are replaced by special bundler functions. So the resulting "bundled" script does not contain any `import/export`, it doesn't require `type="module"`, and we can put it into a regular script:
```html
<!-- Assuming we got bundle.js from a tool like Webpack -->
<script src="bundle.js"></script>
```
## Build tools
In real-life, browser modules are rarely used in their "raw" form. Usually, we bundle them together with a special tool such as [Webpack](https://webpack.js.org/) and deploy to the production server.
@ -357,13 +357,20 @@ Build tools do the following:
- Modern, bleeding-edge JavaScript syntax may be transformed to older one with similar functionality using [Babel](https://babeljs.io/).
- The resulting file is minified (spaces removed, variables replaced with shorter named etc).
If we use bundle tools, then as scripts are bundled together into a single file (or few files), `import/export` statements inside those scripts are replaced by special bundler functions. So the resulting "bundled" script does not contain any `import/export`, it doesn't require `type="module"`, and we can put it into a regular script:
```html
<!-- Assuming we got bundle.js from a tool like Webpack -->
<script src="bundle.js"></script>
```
That said, native modules are also usable. So we won't be using Webpack here: you can configure it later.
## Summary
To summarize, the core concepts are:
1. A module is a file. To make `import/export` work, browsers need `<script type="module">`, that implies several differences:
1. A module is a file. To make `import/export` work, browsers need `<script type="module">`. Modules have several differences:
- Deferred by default.
- Async works on inline scripts.
- To load external scripts from another origin (domain/protocol/port), CORS headers are needed.
@ -372,7 +379,7 @@ To summarize, the core concepts are:
3. Modules always `use strict`.
4. Module code is executed only once. Exports are created once and shared between importers.
So, generally, when we use modules, each module implements the functionality and exports it. Then we use `import` to directly import it where it's needed. Browser loads and evaluates the scripts automatically.
When we use modules, each module implements the functionality and exports it. Then we use `import` to directly import it where it's needed. Browser loads and evaluates the scripts automatically.
In production, people often use bundlers such as [Webpack](https://webpack.js.org) to bundle modules together for performance and other reasons.

View file

@ -8,15 +8,25 @@ libs:
The backbone of an HTML document are tags.
According to Document Object Model (DOM), every HTML-tag is an object. Nested tags are called "children" of the enclosing one.
According to Document Object Model (DOM), every HTML-tag is an object. Nested tags are "children" of the enclosing one. The text inside a tag it is an object as well.
The text inside a tag it is an object as well.
All these objects are accessible using JavaScript, we can use them to modify the page.
All these objects are accessible using JavaScript.
For example, `document.body` is the object representing `<body>` tag.
Running this code will make the `<body>` red for 3 seconds:
```js run
document.body.style.background = 'red'; // make the background red
setTimeout(() => document.body.style.background = '', 3000); // return back
```
That was just a glimpse of DOM power. Soon we'll learn more ways to manipulate DOM, but first we need to know about its structure.
## An example of DOM
For instance, let's explore the DOM for this document:
Let's start with the following simple docment:
```html run no-beautify
<!DOCTYPE HTML>
@ -44,7 +54,9 @@ drawHtmlTree(node1, 'div.domtree', 690, 320);
On the picture above, you can click on element nodes and their children will open/collapse.
```
Tags are called *element nodes* (or just elements). Nested tags become children of the enclosing ones. As a result we have a tree of elements: `<html>` is at the root, then `<head>` and `<body>` are its children, etc.
Every tree node is an object.
Tags are *element nodes* (or just elements), they form the tree structure: `<html>` is at the root, then `<head>` and `<body>` are its children, etc.
The text inside elements forms *text nodes*, labelled as `#text`. A text node contains only a string. It may not have children and is always a leaf of the tree.
@ -55,7 +67,7 @@ Please note the special characters in text nodes:
- a newline: `↵` (in JavaScript known as `\n`)
- a space: `␣`
Spaces and newlines -- are totally valid characters, they form text nodes and become a part of the DOM. So, for instance, in the example above the `<head>` tag contains some spaces before `<title>`, and that text becomes a `#text` node (it contains a newline and some spaces only).
Spaces and newlines -- are totally valid characters, like letters and digits. They form text nodes and become a part of the DOM. So, for instance, in the example above the `<head>` tag contains some spaces before `<title>`, and that text becomes a `#text` node (it contains a newline and some spaces only).
There are only two top-level exclusions:
1. Spaces and newlines before `<head>` are ignored for historical reasons,
@ -78,15 +90,14 @@ let node2 = {"name":"HTML","nodeType":1,"children":[{"name":"HEAD","nodeType":1,
drawHtmlTree(node2, 'div.domtree', 690, 210);
</script>
```smart header="Edge spaces and in-between empty text are usually hidden in tools"
```smart header="Spaces at string start/end and space-only text nodes are usually hidden in tools"
Browser tools (to be covered soon) that work with DOM usually do not show spaces at the start/end of the text and empty text nodes (line-breaks) between tags.
That's because they are mainly used to decorate HTML, and do not affect how it is shown (in most cases).
Developer tools save screen space this way.
On further DOM pictures we'll sometimes omit them where they are irrelevant, to keep things short.
On further DOM pictures we'll sometimes omit them when they are irrelevant. Such spaces usually do not affect how the document is displayed.
```
## Autocorrection
If the browser encounters malformed HTML, it automatically corrects it when making DOM.
@ -148,7 +159,9 @@ You see? The `<tbody>` appeared out of nowhere. You should keep this in mind whi
## Other node types
Let's add more tags and a comment to the page:
There are some other node types besides elements and text nodes.
For example, comments:
```html
<!DOCTYPE HTML>
@ -174,7 +187,7 @@ let node6 = {"name":"HTML","nodeType":1,"children":[{"name":"HEAD","nodeType":1,
drawHtmlTree(node6, 'div.domtree', 690, 500);
</script>
Here we see a new tree node type -- *comment node*, labeled as `#comment`.
We can see here a new tree node type -- *comment node*, labeled as `#comment`, between two text nodes.
We may think -- why is a comment added to the DOM? It doesn't affect the visual representation in any way. But there's a rule -- if something's in HTML, then it also must be in the DOM tree.
@ -195,8 +208,6 @@ There are [12 node types](https://dom.spec.whatwg.org/#node). In practice we usu
To see the DOM structure in real-time, try [Live DOM Viewer](http://software.hixie.ch/utilities/js/live-dom-viewer/). Just type in the document, and it will show up DOM at an instant.
## In the browser inspector
Another way to explore the DOM is to use the browser developer tools. Actually, that's what we use when developing.
To do so, open the web-page [elks.html](elks.html), turn on the browser developer tools and switch to the Elements tab.
@ -225,10 +236,12 @@ The best way to study them is to click around. Most values are editable in-place
## Interaction with console
As we explore the DOM, we also may want to apply JavaScript to it. Like: get a node and run some code to modify it, to see the result. Here are few tips to travel between the Elements tab and the console.
As we work the DOM, we also may want to apply JavaScript to it. Like: get a node and run some code to modify it, to see the result. Here are few tips to travel between the Elements tab and the console.
- Select the first `<li>` in the Elements tab.
- Press `key:Esc` -- it will open console right below the Elements tab.
For the start:
1. Select the first `<li>` in the Elements tab.
2. Press `key:Esc` -- it will open console right below the Elements tab.
Now the last selected element is available as `$0`, the previously selected is `$1` etc.
@ -236,9 +249,11 @@ We can run commands on them. For instance, `$0.style.background = 'red'` makes t
![](domconsole0.png)
From the other side, if we're in console and have a variable referencing a DOM node, then we can use the command `inspect(node)` to see it in the Elements pane.
That's how to get a node from Elements in Console.
Or we can just output it in the console and explore "at-place", like `document.body` below:
There's also a road back. If there's a variable referencing a DOM node, then we can use the command `inspect(node)` in Console to see it in the Elements pane.
Or we can just output DOM-node in the console and explore "at-place", like `document.body` below:
![](domconsole1.png)

View file

@ -9,7 +9,7 @@ libs:
The DOM allows us to do anything with elements and their contents, but first we need to reach the corresponding DOM object.
All operations on the DOM start with the `document` object. From it we can access any node.
All operations on the DOM start with the `document` object. That's the main "entry point" to DOM. From it we can access any node.
Here's a picture of links that allow for travel between DOM nodes:
@ -86,9 +86,9 @@ For instance, here `<body>` has children `<div>` and `<ul>` (and few blank text
</html>
```
...And all descendants of `<body>` are not only direct children `<div>`, `<ul>` but also more deeply nested elements, such as `<li>` (a child of `<ul>`) and `<b>` (a child of `<li>`) -- the entire subtree.
...And descendants of `<body>` are not only direct children `<div>`, `<ul>` but also more deeply nested elements, such as `<li>` (a child of `<ul>`) and `<b>` (a child of `<li>`) -- the entire subtree.
**The `childNodes` collection provides access to all child nodes, including text nodes.**
**The `childNodes` collection lists all child nodes, including text nodes.**
The example below shows children of `document.body`:
@ -182,21 +182,26 @@ Please, don't. The `for..in` loop iterates over all enumerable properties. And c
## Siblings and the parent
*Siblings* are nodes that are children of the same parent. For instance, `<head>` and `<body>` are siblings:
*Siblings* are nodes that are children of the same parent.
For instance, here `<head>` and `<body>` are siblings:
```html
<html>
<head>...</head><body>...</body>
</html>
```
- `<body>` is said to be the "next" or "right" sibling of `<head>`,
- `<head>` is said to be the "previous" or "left" sibling of `<body>`.
The next sibling is is `nextSibling`, and the previous one is `previousSibling`.
The parent is available as `parentNode`.
The next node in the same parent (next sibling) is `nextSibling`, and the previous one is `previousSibling`.
For instance:
```html run
<html><head></head><body><script>
// HTML is "dense" to evade extra "blank" text nodes.
So all these tests are truthy:
```js
// parent of <body> is <html>
alert( document.body.parentNode === document.documentElement ); // true
@ -205,7 +210,6 @@ For instance:
// before <body> goes <head>
alert( document.body.previousSibling ); // HTMLHeadElement
</script></body></html>
```
## Element-only navigation
@ -235,12 +239,12 @@ alert( document.documentElement.parentNode ); // document
alert( document.documentElement.parentElement ); // null
```
In other words, the `documentElement` (`<html>`) is the root node. Formally, it has `document` as its parent. But `document` is not an element node, so `parentNode` returns it and `parentElement` does not.
The reason is that root node `document.documentElement` (`<html>`) has `document` as its parent. But `document` is not an element node, so `parentNode` returns it and `parentElement` does not.
This loop travels up from an arbitrary element `elem` to `<html>`, but not to the `document`:
This detail may be useful when we want to travel up from an arbitrary element `elem` to `<html>`, but not to the `document`:
```js
while(elem = elem.parentElement) {
alert( elem ); // parent chain till <html>
while(elem = elem.parentElement) { // go up till <html>
alert( elem );
}
```
````

View file

@ -11,15 +11,15 @@ table.getElementsByTagName('label')
// or
document.querySelectorAll('#age-table label')
// 3. The first td in that table (with the word "Age").
// 3. The first td in that table (with the word "Age")
table.rows[0].cells[0]
// or
table.getElementsByTagName('td')[0]
// or
table.querySelector('td')
// 4. The form with the name "search".
// assuming there's only one element with name="search"
// 4. The form with the name "search"
// assuming there's only one element with name="search" in the document
let form = document.getElementsByName('search')[0]
// or, form specifically
document.querySelector('form[name="search"]')
@ -29,8 +29,7 @@ form.getElementsByTagName('input')[0]
// or
form.querySelector('input')
// 6. The last input in that form.
// there's no direct query for that
let inputs = form.querySelectorAll('input') // search all
inputs[inputs.length-1] // take last
// 6. The last input in that form
let inputs = form.querySelectorAll('input') // find all inputs
inputs[inputs.length-1] // take the last one
```

View file

@ -6,12 +6,12 @@ importance: 4
Here's the document with the table and form.
How to find?
How to find?...
1. The table with `id="age-table"`.
2. All `label` elements inside that table (there should be 3 of them).
3. The first `td` in that table (with the word "Age").
4. The `form` with the name `search`.
4. The `form` with `name="search"`.
5. The first `input` in that form.
6. The last `input` in that form.

View file

@ -105,7 +105,7 @@ Pseudo-classes in the CSS selector like `:hover` and `:active` are also supporte
The call to `elem.querySelector(css)` returns the first element for the given CSS selector.
In other words, the result is the same as `elem.querySelectorAll(css)[0]`, but the latter is looking for *all* elements and picking one, while `elem.querySelector` just looks for one. So it's faster and shorter to write.
In other words, the result is the same as `elem.querySelectorAll(css)[0]`, but the latter is looking for *all* elements and picking one, while `elem.querySelector` just looks for one. So it's faster and also shorter to write.
## matches

Binary file not shown.