You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
5
5
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.
7
7
8
-
That leads to two important issues:
8
+
Questo conduce a 2 importanti problematiche:
9
9
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:
<!-- This isn't visible until the script loads -->
19
-
<p>...content after script...</p>
19
+
<p>...contenuto dopo lo script...</p>
20
20
```
21
21
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:
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.
33
33
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.
35
35
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`.
37
37
38
38
## defer
39
39
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.
41
41
42
-
Here's the same example as above, but with`defer`:
42
+
Di seguito lo stesso esempio di sopra, ma con`defer`:
```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.
84
84
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.
86
86
```
87
87
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`.
90
90
```
91
91
92
92
93
93
## async
94
94
95
-
The `async` attribute means that a script is completely independent:
95
+
L'attributo `async` indica che uno script è completamente indipendente:
96
96
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
98
98
- `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.
102
102
103
103
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:
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".
122
122
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:
124
124
125
125
```html
126
-
<!-- Google Analytics is usually added like this-->
126
+
<!-- Google Analytics viene aggiunto in questo modo di solito-->
We can also add a script dynamically using JavaScript:
133
+
Possiamo anche aggiungere uno script dinamicamente usando Javascript:
134
134
135
135
```js run
136
136
let script =document.createElement('script');
137
137
script.src="/article/script-async-defer/long.js";
138
138
document.body.append(script); // (*)
139
139
```
140
140
141
-
The script starts loading as soon as it's appended to the document `(*)`.
141
+
Lo script inizia a caricarsi quando è allegato al document `(*)`.
142
142
143
-
**Dynamic scripts behave as "async" by default.**
143
+
**Gli script dinamici si comportano come quelli "async" di default.**
144
144
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")
148
148
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`:
150
150
151
151
```js run
152
152
let script =document.createElement('script');
@@ -159,8 +159,7 @@ script.async = false;
159
159
document.body.append(script);
160
160
```
161
161
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":
164
163
165
164
```js run
166
165
functionloadScript(src) {
@@ -170,29 +169,29 @@ function loadScript(src) {
170
169
document.body.append(script);
171
170
}
172
171
173
-
// long.js runs first because of async=false
172
+
// long.js viene eseguito per primo grazie a async=false
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.
182
181
183
-
But there are also essential differences between them:
182
+
Ma ci sono anche differenze essenziali tra loro:
184
183
185
184
|| Order |`DOMContentLoaded`|
186
185
|---------|---------|---------|
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`. |
189
188
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.
192
191
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.
194
193
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.
196
195
```
197
196
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.
0 commit comments