Skip to content

Commit eea56ce

Browse files
committed
SCRIPT ASYNC DEFER
1 parent fa74de2 commit eea56ce

File tree

2 files changed

+66
-67
lines changed

2 files changed

+66
-67
lines changed
Lines changed: 65 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,152 +1,152 @@
11

22
# Scripts: async, defer
33

4-
In modern websites, scripts are often "heavier" than HTML: their download size is larger, and processing time is also longer.
4+
Nei moderni browser gli script sono spesso "più pesanti" dell'HTML: la loro dimensione di download è maggiore e anche i tempi di processamento sono più lunghi.
55

6-
When the browser loads HTML and comes across a `<script>...</script>` tag, it can't continue building DOM. It must execute the script right now. The same happens for external scripts `<script src="..."></script>`: the browser must wait until the script downloads, execute it, and only after process the rest of the page.
6+
Quando il browser carica l'HTML e si imbatte in un tag `<script>...</script>` non può continuare a costruire il DOM. Deve eseguire lo script al momento. Lo stesso avviene per script esterni `<script src="..."></script>`: il browser deve aspettere che lo script venga scaricato, eseguito e solo dopo può processare il resto della pagina.
77

8-
That leads to two important issues:
8+
Questo conduce a 2 importanti problematiche:
99

10-
1. Scripts can't see DOM elements below them, so can't add handlers etc.
11-
2. If there's a bulky script at the top of the page, it "blocks the page". Users can't see the page content till it downloads and runs:
10+
1. Gli script non possono vedere gli elementi del DOM sotto di essi e quindi non possono aggiungere handler,ecc.
11+
2. Se c'è uno script di grandi dimensioni all'inzio della pagina esso "bloccherà la pagina". Gli utente non potranno vedere il contenuto della pagina fino a quando lo script verrà scaricato ed eseguito:
1212

1313
```html run height=100
14-
<p>...content before script...</p>
14+
<p>...contenuto prima dello script...</p>
1515

1616
<script src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script>
1717

1818
<!-- This isn't visible until the script loads -->
19-
<p>...content after script...</p>
19+
<p>...contenuto dopo lo script...</p>
2020
```
2121

22-
There are some workarounds to that. For instance, we can put a script at the bottom of the page. Then it can see elements above it, and it doesn't block the page content from showing:
22+
Ci sono alcuni accorgimenti per avere il comportamente desiderato. Per esempio, possiamo mettere lo script in fondo alla pagina. In questo modo vedrà gli elementi sopra di esso e non bloccherà la visualizzazione della pagina:
2323

2424
```html
2525
<body>
26-
...all content is above the script...
26+
...tutto il contenuto è prima dello script...
2727

2828
<script src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script>
2929
</body>
3030
```
3131

32-
But this solution is far from perfect. For example, the browser notices the script (and can start downloading it) only after it downloaded the full HTML document. For long HTML documents, that may be a noticeable delay.
32+
Ma questa soluzione è lontana dall'essere perfetta. Per esempio, il browser si accorge dello script (e può iniziarlo a scaricare) solo dopo che è stato scaricato tutto il documento HTML. Per pagine HTML molto lunghe ci potrebbe essere un notevole ritardo nel caricamento dello script.
3333

34-
Such things are invisible for people using very fast connections, but many people in the world still have slower internet speeds and use far-from-perfect mobile internet.
34+
Such things are invisible for people using very fast connections, but many people in the world still have slower internet speeds and use far-from-perfect mobile internet. Queste cose sono invisibili per persone che utilizzano una connessione molto veloce ma molte persone nel mondo hanno ancora una connessione Internet più lenta e utilizzano connessioni mobile molto scarse.
3535

36-
Luckily, there are two `<script>` attributes that solve the problem for us: `defer` and `async`.
36+
Fortunatamente, ci sono 2 attributi del tag `<script>` che risolvono il problema per noi: `defer` e `async`.
3737

3838
## defer
3939

40-
The `defer` attribute tells the browser that it should go on working with the page, and load the script "in background", then run the script when it loads.
40+
L'attributo `defer` dice al browser che che deve continuare nel caricamento della pagina e caricare lo script "in background", per poi eseguire lo script quando è caricato.
4141

42-
Here's the same example as above, but with `defer`:
42+
Di seguito lo stesso esempio di sopra, ma con `defer`:
4343

4444
```html run height=100
45-
<p>...content before script...</p>
45+
<p>...contenuto prima dello script...</p>
4646

4747
<script defer src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script>
4848

4949
<!-- visible immediately -->
50-
<p>...content after script...</p>
50+
<p>...contenuto dopo lo script...</p>
5151
```
5252

53-
- Scripts with `defer` never block the page.
54-
- Scripts with `defer` always execute when the DOM is ready, but before `DOMContentLoaded` event.
53+
- Gli script con `defer` non bloccano mai la pagina
54+
- Gli script con `defer` vengono sempre eseguiti quando il DOM è pronto, ma prima dell'evento `DOMContentLoaded`.
5555

56-
The following example demonstrates that:
56+
Il seguente esempio lo dimostra:
5757

5858
```html run height=100
59-
<p>...content before scripts...</p>
59+
<p>...contenuto prima dello script...</p>
6060

6161
<script>
62-
document.addEventListener('DOMContentLoaded', () => alert("DOM ready after defer!")); // (2)
62+
document.addEventListener('DOMContentLoaded', () => alert("DOM pronto dopo defer!")); // (2)
6363
</script>
6464

6565
<script defer src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script>
6666

67-
<p>...content after scripts...</p>
67+
<p>...contenuto dopo lo script...</p>
6868
```
6969

70-
1. The page content shows up immediately.
71-
2. `DOMContentLoaded` waits for the deferred script. It only triggers when the script `(2)` is downloaded is executed.
70+
1. Il contenuto della pagina viene visualizzato immediatamente.
71+
2. `DOMContentLoaded` aspetta il caricamento degli script con l'attributo defer. Scatta solo quando lo script `(2)` è scaricato ed eseguito.
7272

73-
Deferred scripts keep their relative order, just like regular scripts.
73+
Gli script con defer mantengono il loro ordine, come avviene per i normali script
7474

75-
So, if we have a long script first, and then a smaller one, then the latter one waits.
75+
Quindi, se abbiamo prima uno script lungo e poi uno più piccolo, quest'ultimo dovrà aspettare.
7676

7777
```html
7878
<script defer src="https://javascript.info/article/script-async-defer/long.js"></script>
7979
<script defer src="https://javascript.info/article/script-async-defer/small.js"></script>
8080
```
8181

82-
```smart header="The small script downloads first, runs second"
83-
Browsers scan the page for scripts and download them in parallel, to improve performance. So in the example above both scripts download in parallel. The `small.js` probably makes it first.
82+
```smart header="Lo script piccolo viene scaricato prima, ma eseguito per secondo"
83+
I browser scansionano la pagina per trovare gli script e li scarica in parallelo, per migliorare le performance. Quindi nell'esempio sopra entrambi gli script sono scaricati in parallelo. `small.js` probabilmente verrà scaricato prima.
8484
85-
But the specification requires scripts to execute in the document order, so it waits for `long.js` to execute.
85+
Ma le specifiche indicano che gli script devono essere eseguito secondo l'ordine nel document, quindi `small.js` aspetterà `long.js` per essere eseguito.
8686
```
8787

88-
```smart header="The `defer` attribute is only for external scripts"
89-
The `defer` attribute is ignored if the `<script>` tag has no `src`.
88+
```smart header="L'attributo `defer` è valido solo per script esterni
89+
L'attributo `defer` viene ignorato se il tag `<script>` non ha l'attributo `src`.
9090
```
9191
9292
9393
## async
9494
95-
The `async` attribute means that a script is completely independent:
95+
L'attributo `async` indica che uno script è completamente indipendente:
9696
97-
- The page doesn't wait for async scripts, the contents is processed and displayed.
97+
- La pagina non aspetta gli script con async, il contenuto viene processato e visualizzato
9898
- `DOMContentLoaded` and async scripts don't wait each other:
99-
- `DOMContentLoaded` may happen both before an async script (if an async script finishes loading after the page is complete)
100-
- ...or after an async script (if an async script is short or was in HTTP-cache)
101-
- Other scripts don't wait for `async` scripts, and `async` scripts don't wait for them.
99+
- `DOMContentLoaded` può scattare prima di uno script async (se lo script finisce di caricarsi dopo che il caricamento della pagina è terminato)
100+
- ...o dopo uno script `async` (se lo script è corto o era cachato)
101+
- Anche gli altri script non aspettano il caricamento degli script `async`, e gli script `async` non aspettano il caricamento degli altri script.
102102
103103
104-
So, if we have several `async` scripts, they may execute in any order. Whatever loads first -- runs first:
104+
Quindi, se abbiamo parecchi script `async`, potrebbero essere eseguiti in qualunque ordine. Qualunque di essi viene caricato prima -- viene eseguito prima:
105105
106106
```html run height=100
107-
<p>...content before scripts...</p>
107+
<p>...contenuto prima degli script...</p>
108108
109109
<script>
110-
document.addEventListener('DOMContentLoaded', () => alert("DOM ready!"));
110+
document.addEventListener('DOMContentLoaded', () => alert("DOM pronto!"));
111111
</script>
112112
113113
<script async src="https://javascript.info/article/script-async-defer/long.js"></script>
114114
<script async src="https://javascript.info/article/script-async-defer/small.js"></script>
115115
116-
<p>...content after scripts...</p>
116+
<p>...contenuto dopo gli script...</p>
117117
```
118118

119-
1. The page content shows up immediately: `async` doesn't block it.
120-
2. `DOMContentLoaded` may happen both before and after `async`, no guarantees here.
121-
3. Async scripts don't wait for each other. A smaller script `small.js` goes second, but probably loads before `long.js`, so runs first. That's called a "load-first" order.
119+
1. Il contenuto della pagina viene mostrato immediatamente: l'attributo `async` non lo blocca.
120+
2. `DOMContentLoaded` potrebbe scattare sia prima che dopo gli script `async`, non c'è nesusna garanzia in questo caso.
121+
3. Gli script async non si aspettano a vicenda. Uno script più piccolo come `small.js` è stato inserito nella pagina per secondo ma probabilmente verrà caricato prima di `long.js` e quindi anche eseguito per primo. Questo viene chiamato un ordine "load-first".
122122

123-
Async scripts are great when we integrate an independent third-party script into the page: counters, ads and so on, as they don't depend on our scripts, and our scripts shouldn't wait for them:
123+
Gli script async sono ottimali quando dobbiamo integrare uno script di terze parti indipendente: contatori, ads, e così via, visto che essi non dipendono dai nostri script e i nostri script non devono aspettare il loro caricamento:
124124

125125
```html
126-
<!-- Google Analytics is usually added like this -->
126+
<!-- Google Analytics viene aggiunto in questo modo di solito -->
127127
<script async src="https://google-analytics.com/analytics.js"></script>
128128
```
129129

130130

131-
## Dynamic scripts
131+
## Script dinamici
132132

133-
We can also add a script dynamically using JavaScript:
133+
Possiamo anche aggiungere uno script dinamicamente usando Javascript:
134134

135135
```js run
136136
let script = document.createElement('script');
137137
script.src = "/article/script-async-defer/long.js";
138138
document.body.append(script); // (*)
139139
```
140140

141-
The script starts loading as soon as it's appended to the document `(*)`.
141+
Lo script inizia a caricarsi quando è allegato al document `(*)`.
142142

143-
**Dynamic scripts behave as "async" by default.**
143+
**Gli script dinamici si comportano come quelli "async" di default.**
144144

145-
That is:
146-
- They don't wait for anything, nothing waits for them.
147-
- The script that loads first -- runs first ("load-first" order).
145+
Cioè:
146+
- Non aspettano nessun altro script e nessuno aspetta loro.
147+
- Lo script che viene caricato per prima viene anche eseguito per primo (ordine "load-first")
148148

149-
We can change the load-first order into the document order (just like regular scripts) by explicitly setting `async` property to `false`:
149+
Possiamo cambiare l'ordine "load-first" nell'ordine del document (come i normali script) settando l'attributo `async` a `false`:
150150

151151
```js run
152152
let script = document.createElement('script');
@@ -159,8 +159,7 @@ script.async = false;
159159
document.body.append(script);
160160
```
161161

162-
For example, here we add two scripts. Without `script.async=false` they would execute in load-first order (the `small.js` probably first). But with that flag the order is "as in the document":
163-
162+
Per esempio, in questo caso abbiamo aggiunto 2 script. Senza `script.async=false` verrebbero eseguito secondo l'ordine load-first (`small.js` probabilmente per primo). Ma con quel flag l'ordine diventa "come nel documento":
164163

165164
```js run
166165
function loadScript(src) {
@@ -170,29 +169,29 @@ function loadScript(src) {
170169
document.body.append(script);
171170
}
172171

173-
// long.js runs first because of async=false
172+
// long.js viene eseguito per primo grazie a async=false
174173
loadScript("/article/script-async-defer/long.js");
175174
loadScript("/article/script-async-defer/small.js");
176175
```
177176

178177

179-
## Summary
178+
## Riepilogo
180179

181-
Both `async` and `defer` have one common thing: downloading of such scripts doesn't block page rendering. So the user can read page content and get acquanted with the page immediately.
180+
`async` e `defer` hanno una cosa in comune: il download di questi script non blocca il rendering della pagina. Quindi l'utente può leggere e comprendere il contenuto della pagina immediatamente.
182181

183-
But there are also essential differences between them:
182+
Ma ci sono anche differenze essenziali tra loro:
184183

185184
| | Order | `DOMContentLoaded` |
186185
|---------|---------|---------|
187-
| `async` | *Load-first order*. Their document order doesn't matter -- which loads first | Irrelevant. May load and execute while the document has not yet been fully downloaded. That happens if scripts are small or cached, and the document is long enough. |
188-
| `defer` | *Document order* (as they go in the document). | Execute after the document is loaded and parsed (they wait if needed), right before `DOMContentLoaded`. |
186+
| `async` | *Load-first order*. Il loro ordine nel documento non importa -- dipende da quale script viene caricato prima | Irrelevante. Potrebbe essere caricato ed eseguito mentre la pagina non è stata ancora stata scaricata. Questo avviene se gli script sono piccoli o cachati, e la pagina è abbastanza lunga. |
187+
| `defer` | *Document order* (cioè come sono posizionati nella pagina). |Vengono eseguiti dopo che il document è stato caricato e parsato (aspettano se necessario), poco prima dell'evento `DOMContentLoaded`. |
189188

190-
```warn header="Page without scripts should be usable"
191-
Please note that if you're using `defer`, then the page is visible *before* the script loads.
189+
```warn header="Una pagina senza script dovrebbe essere utilizzabile"
190+
Ricordati che se stai usando `defer`, allora la pagina è visibile *prima* che lo script sia caricato.
192191
193-
So the user may read the page, but some graphical components are probably not ready yet.
192+
Quindi l'utente potrebbe leggere la pagina ma probabilmente alcuni componenti grafici potrebbero essere non ancora pronti.
194193
195-
There should be "loading" indication in proper places, not-working buttons disabled, to clearly show the user what's ready and what's not.
194+
Dovrebbero esserci delle indicazioni di "caricamento" negli appositi spazi, i bottoni non funzionanti dovrebbero essere disabilitati, per mostrare chiaramente all'utente cosa è già pronto o cosa no.
196195
```
197196

198-
In practice, `defer` is used for scripts that need the whole DOM and/or their relative execution order is important. And `async` is used for independent scripts, like counters or ads. And their relative execution order does not matter.
197+
In pratica, `defer` è utilizzato per script che hanno bisogno di tutto il DOM e/o l'ordine di esecuzione è importante. `async` è utilizzato per script indipendenti, come contatori o ads. E il loro ordine relative di esecuzione non conta.

2-ui/5-loading/index.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11

2-
# Document and resource loading
2+
# Document e caricamento delle risorse

0 commit comments

Comments
 (0)