Skip to content

Commit 9ca658d

Browse files
authored
Merge pull request #82 from simoneP93/resourceLoading
onload/onerror
2 parents 448336a + f74f9e0 commit 9ca658d

File tree

3 files changed

+78
-78
lines changed

3 files changed

+78
-78
lines changed
Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11

2-
The algorithm:
3-
1. Make `img` for every source.
4-
2. Add `onload/onerror` for every image.
5-
3. Increase the counter when either `onload` or `onerror` triggers.
6-
4. When the counter value equals to the sources count -- we're done: `callback()`.
2+
L'algoritmo:
3+
1. Fare un `img` per ogni sorgente.
4+
2. Aggiungere `onload/onerror` ad ogni immagine.
5+
3. Incrementa il contatore quando si aziona `onload` o `onerror`.
6+
4. Quando il valore del contatore è uguale al numero delle sorgenti abbiamo finito: `callback()`.

2-ui/5-loading/03-onload-onerror/1-load-img-callback/task.md

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,22 @@ importance: 4
22

33
---
44

5-
# Load images with a callback
5+
# Caricare immagini con una callback
66

7-
Normally, images are loaded when they are created. So when we add `<img>` to the page, the user does not see the picture immediately. The browser needs to load it first.
7+
Normalmente, le immagini vengono caricate quando sono create. Quindi quando aggiungiamo `<img>` alla pagina, l'utente non vede l'immagine immediatamente. Il Browser deve prima caricarla.
88

9-
To show an image immediately, we can create it "in advance", like this:
9+
Per visualizzare un'immagine immediatamente dobbiamo crearla "in anticipo", come in questo caso:
1010

1111
```js
1212
let img = document.createElement('img');
1313
img.src = 'my.jpg';
1414
```
1515

16-
The browser starts loading the image and remembers it in the cache. Later, when the same image appears in the document (no matter how), it shows up immediately.
16+
Il browser inizia a caricare l'immagine e la salva nella cache. In seguito, quando la stessa immagine comparirà nel document, si visualizzerà immediatamente.
1717

18-
**Create a function `preloadImages(sources, callback)` that loads all images from the array `sources` and, when ready, runs `callback`.**
18+
**Crea una funzione `preloadImages(sources, callback)` che carica tutte le immagini da un array `sources` e, quando pronte, esegue `callback`.**
1919

20-
For instance, this will show an `alert` after the images are loaded:
20+
Per esempio, questo pezzo di codice visualizzerà un `alert` dopo che le immagini sono caricate:
2121

2222
```js
2323
function loaded() {
@@ -27,10 +27,10 @@ function loaded() {
2727
preloadImages(["1.jpg", "2.jpg", "3.jpg"], loaded);
2828
```
2929

30-
In case of an error, the function should still assume the picture "loaded".
30+
In caso di errore la funzione dovrebbe comunque considerare l'immagine "caricata"
3131

32-
In other words, the `callback` is executed when all images are either loaded or errored out.
32+
In altre parole, la funzione di `callback` è eseguita quando tutte le immagini sono caricate o sono andate in errore.
3333

34-
The function is useful, for instance, when we plan to show a gallery with many scrollable images, and want to be sure that all images are loaded.
34+
La funzione, ad esempio, è utile quando dobbiamo mostrare una galleria scrollabile di immagini e vogliamo essere sicuri che tutte le immagini siano caricate.
3535

36-
In the source document you can find links to test images, and also the code to check whether they are loaded or not. It should output `300`.
36+
Nel documento sorgente puoi trovare i link alle immagini di test ed anche il codice per verificare se le immagini sono state caricate o meno. L'output dovrebbe essere `300`.
Lines changed: 63 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
1-
# Resource loading: onload and onerror
1+
# Caricamento delle risorse: onload e onerror
22

3-
The browser allows to track the loading of external resources -- scripts, iframes, pictures and so on.
3+
Il browser permette di tracciare il caricamente di risorse esterne -- script, iframe, immagini e così via.
44

5-
There are two events for it:
5+
Esistono 2 eventi per tracciare il caricamento:
66

7-
- `onload` -- successful load,
8-
- `onerror` -- an error occurred.
7+
- `onload` -- caricato con success,
8+
- `onerror` -- si è verificato un errore.
99

10-
## Loading a script
10+
## Caricamento di uno script
1111

12-
Let's say we need to load a third-party script and call a function that resides there.
12+
Diciamo che abbiamo necessità di caricare uno script di terze parti e chiamare una funzione che appartiene a questo script.
1313

14-
We can load it dynamically, like this:
14+
Possiamo caricarlo dinamicamente, in questo modo:
1515

1616
```js
1717
let script = document.createElement('script');
@@ -20,106 +20,106 @@ script.src = "my.js";
2020
document.head.append(script);
2121
```
2222

23-
...But how to run the function that is declared inside that script? We need to wait until the script loads, and only then we can call it.
23+
...Ma come possiamo eseguire la funzione dichiarata all'interno di quello script? Dobbiamo attendere finchè lo script sia caricato e solo allora possiamo chiamare la funzione.
2424

2525
```smart
26-
For our own scripts we could use [JavaScript modules](info:modules) here, but they are not widely adopted by third-party libraries.
26+
Per i nostri script dovremmo utilizzare i [moduli JavaScript](info:modules) in questo caso, ma non sono largamente adottati dalle librerie di terze parti.
2727
```
2828

2929
### script.onload
3030

31-
The main helper is the `load` event. It triggers after the script was loaded and executed.
31+
Il principale helper è l'evento `load`. Si innesca dopo che lo script è stato caricato ed eseguito.
3232

33-
For instance:
33+
Per esempio:
3434

3535
```js run untrusted
3636
let script = document.createElement('script');
3737

38-
// can load any script, from any domain
38+
// si può caricare qualunque script, da qualunque dominio
3939
script.src = "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.3.0/lodash.js"
4040
document.head.append(script);
4141

4242
*!*
4343
script.onload = function() {
44-
// the script creates a helper function "_"
45-
alert(_); // the function is available
44+
// lo script crea una funzione helper "_"
45+
alert(_); // la funzione è disponibile
4646
};
4747
*/!*
4848
```
4949

50-
So in `onload` we can use script variables, run functions etc.
50+
Quindi nell'evento `onload` possiamo utilizzare le variabili dello script, eseguire funzioni, ecc.
5151

52-
...And what if the loading failed? For instance, there's no such script (error 404) or the server or the server is down (unavailable).
52+
...E cosa accade se il caricamento fallisce? Per esempio, quello script non esiste sul server (errore 404) o il server è fuori servizio (non disponibile).
5353

5454
### script.onerror
5555

56-
Errors that occur during the loading of the script can be tracked on `error` event.
56+
Gli errori che si verificano durante il caricamento dello script possono essere tracciati tramite l'evento `error`.
5757

58-
For instance, let's request a script that doesn't exist:
58+
Per esempio, proviamo a richiedere uno script che non esiste:
5959

6060
```js run
6161
let script = document.createElement('script');
62-
script.src = "https://example.com/404.js"; // no such script
62+
script.src = "https://example.com/404.js"; // script che non esiste
6363
document.head.append(script);
6464

6565
*!*
6666
script.onerror = function() {
67-
alert("Error loading " + this.src); // Error loading https://example.com/404.js
67+
alert("Caricamento fallito " + this.src); // Error loading https://example.com/404.js
6868
};
6969
*/!*
7070
```
7171

72-
Please note that we can't get HTTP error details here. We don't know was it error 404 or 500 or something else. Just that the loading failed.
72+
Notate bene che in questo punto non possiamo ottenere i dettagli dell'errore HTTP. Non sappiamo se è un errore 404 o 500 o qualcos'altro.
7373

7474
```warn
75-
Events `onload`/`onerror` track only the loading itself.
75+
Gli eventi `onload`/`onerror` tracciano solo il caricamento stesso.
7676
77-
Errors during script processing and execution are out of the scope of these events. To track script errors, one can use `window.onerror` global handler.
77+
Gli errori durante il processamento e l'esecuzione sono fuori dall'ambito di questi eventi. Per tracciare gli errori dello script si può utilizzare l'handler globale `window.onerror`.
7878
```
7979

80-
## Other resources
80+
## Altre risorse
8181

82-
The `load` and `error` events also work for other resources, basically for any resource that has an external `src`.
82+
Gli eventi `load` e `error` funzionano anche per le altre risorse, praticamente per qualunque risorsa che ha un `src` esterno.
8383

84-
For example:
84+
Per esempio:
8585

8686
```js run
8787
let img = document.createElement('img');
8888
img.src = "https://js.cx/clipart/train.gif"; // (*)
8989

9090
img.onload = function() {
91-
alert(`Image loaded, size ${img.width}x${img.height}`);
91+
alert(`Immagine caricata, dimensione ${img.width}x${img.height}`);
9292
};
9393

9494
img.onerror = function() {
95-
alert("Error occurred while loading image");
95+
alert("Si è verificato un errore durante il caricamento dell'immagine");
9696
};
9797
```
9898

99-
There are some notes though:
99+
Ci sono alcune note però:
100100

101-
- Most resources start loading when they are added to the document. But `<img>` is an exception. It starts loading when it gets an src `(*)`.
102-
- For `<iframe>`, the `iframe.onload` event triggers when the iframe loading finished, both for successful load and in case of an error.
101+
- La maggior parte delle risorse inizia a caricarsi quando vengono aggiunte al document, ma `<img>` è un'eccezione. Inizia a caricarsi quando ottiene un src `(*)`.
102+
- Per gli `<iframe>`, l'evento `iframe.onload` si aziona quando il caricamento dell'iframe è terminato, sia in caso di successo che in caso di errore.
103103

104-
That's for historical reasons.
104+
Questo avviene per ragioni storiche.
105105

106106
## Crossorigin policy
107107

108-
There's a rule: scripts from one site can't access contents of the other site. So, e.g. a script at `https://facebook.com` can't read the user's mailbox at `https://gmail.com`.
108+
C'è una regola: gli script di un sito non possono accedere ai contenuti di un altro sito. Quindi, per esempio, uno script di `https://facebook.com` non può leggere la casella di posta dell'utente di `https://gmail.com`.
109109

110-
Or, to be more precise, one origin (domain/port/protocol triplet) can't access the content from another one. So even if we have a subdomain, or just another port, these are different origins, no access to each other.
110+
Per essere più precisi, un'origine (tripletta dominio/porta/protocollo) non può accedere al contenuto di un'altra. Quindi se abbiamo un sottodominio, o anche solo un'altra porta, questo sarà un'origine differente e quindi non hanno accesso l'uno con l'altro.
111111

112-
This rule also affects resources from other domains.
112+
Questa regola interessa anche le risorse di altri domini.
113113

114-
If we're using a script from another domain, and there's an error in it, we can't get error details.
114+
Se stiamo utilizzando uno script di un altro dominio e c'è un errore, non possiamo ottenere i dettagli di quell'errore.
115115

116-
For example, let's take a script `error.js` that consists of a single (bad) function call:
116+
Per esempio, prendiamo lo script `error.js`, che consiste in una singola chiamata ad una funzione (sbagliata):
117117
```js
118118
// 📁 error.js
119119
noSuchFunction();
120120
```
121121

122-
Now load it from the same site where it's located:
122+
Ora caricatela dallo stesso sito su cui è situato lo script:
123123

124124
```html run height=0
125125
<script>
@@ -130,14 +130,14 @@ window.onerror = function(message, url, line, col, errorObj) {
130130
<script src="/article/onload-onerror/crossorigin/error.js"></script>
131131
```
132132

133-
We can see a good error report, like this:
133+
Vedremo il report dell'errore, come questo:
134134

135135
```
136136
Uncaught ReferenceError: noSuchFunction is not defined
137137
https://javascript.info/article/onload-onerror/crossorigin/error.js, 1:1
138138
```
139139

140-
Now let's load the same script from another domain:
140+
Ora carichiamo lo stesso script da un altro dominio:
141141

142142
```html run height=0
143143
<script>
@@ -148,40 +148,40 @@ window.onerror = function(message, url, line, col, errorObj) {
148148
<script src="https://cors.javascript.info/article/onload-onerror/crossorigin/error.js"></script>
149149
```
150150

151-
The report is different, like this:
151+
Il report di errore è diverso rispetto a quello precedente, come questo:
152152

153153
```
154154
Script error.
155155
, 0:0
156156
```
157157

158-
Details may vary depending on the browser, but the idea is same: any information about the internals of a script, including error stack traces, is hidden. Exactly because it's from another domain.
158+
I dettagli potrebbero dipendere dal browser, ma l'idea è la stessa: qualunque informazione interno dello script, incluso lo stack trace dell'errore, è nascosta. Esattamente, perche lo script è di un altro dominio.
159159

160-
Why do we need error details?
160+
Perchè abbiamo bisogno dei dettagli di errore?
161161

162-
There are many services (and we can build our own) that listen to global errors using `window.onerror`, save errors and provide an interface to access and analyze them. That's great, as we can see real errors, triggered by our users. But if a script comes from another origin, then there's no much information about errors in it, as we've just seen.
162+
Ci sono molti servizi (e possiamo anche sviluppare il nostro) che stanno in ascolto sugli errori globali, utilizzando `window.onerror`, salvano gli errori e forniscono un interfaccia per accedere ed analizzarli. Fantastico, possiamo vedere i veri errori, scaturiti dai nostri utenti. Ma se uno script è caricato da un altro dominio non avremo nessuna informazioni sull'errore, come abbiamo appena visto.
163163

164-
Similar cross-origin policy (CORS) is enforced for other types of resources as well.
164+
Una policy cross-origin (CORS) simile viene applicata anche per altri tipi di risorse.
165165

166-
**To allow cross-origin access, the `<script>` tag needs to have `crossorigin` attribute, plus the remote server must provide special headers.**
166+
**Per consentire l'accesso cross-origin il tag `<script>` deve avere l'attributo `crossorigin` e il server remoto deve fornire degli header speciali.**
167167

168-
There are three levels of cross-origin access:
168+
Ci sono tre livelli di accesso cross-origin:
169169

170-
1. **No `crossorigin` attribute** -- access prohibited.
171-
2. **`crossorigin="anonymous"`** -- access allowed if the server responds with the header `Access-Control-Allow-Origin` with `*` or our origin. Browser does not send authorization information and cookies to remote server.
172-
3. **`crossorigin="use-credentials"`** -- access allowed if the server sends back the header `Access-Control-Allow-Origin` with our origin and `Access-Control-Allow-Credentials: true`. Browser sends authorization information and cookies to remote server.
170+
1. **Attributo `crossorigin` non presente** -- accesso vietato.
171+
2. **`crossorigin="anonymous"`** -- accesso consentito se il server risponde con l'header `Access-Control-Allow-Origin` con il valore `*` o il nome della nostra origin (dominio). Il browser non manda dati e cookie sull'autenticazione al server remoto.
172+
3. **`crossorigin="use-credentials"`** -- accesso consentito se il server manda indietro l'header `Access-Control-Allow-Origin` con la nostra origine (dominio) e `Access-Control-Allow-Credentials: true`. Il browser manda i dati e i cookie sull'autenticazione al server remoto.
173173

174174
```smart
175-
You can read more about cross-origin access in the chapter <info:fetch-crossorigin>. It describes `fetch` method for network requests, but the policy is exactly the same.
175+
Può approfondire l'accesso cross-origin nel capitolo <info:fetch-crossorigin>. Descrive il metodo `fetch` per le richieste di rete, ma la policy è esattamente la stessa.
176176
177-
Such thing as "cookies" is out of our current scope, but you can read about them in the chapter <info:cookie>.
177+
Ad esempio i "cookies" sono un argomento fuori dal nostro attuale ambito, ma puoi leggere informazioni a proposito nel capitolo <info:cookie>.
178178
```
179179

180-
In our case, we didn't have any crossorigin attribute. So the cross-origin access was prohibited. Let's add it.
180+
Nel nostro caso non avevamo nessun attributo crossorigin, quindi l'accesso era vietato. Aggiungiamo l'attributo ora.
181181

182-
We can choose between `"anonymous"` (no cookies sent, one server-side header needed) and `"use-credentials"` (sends cookies too, two server-side headers needed).
182+
Possiamo scegliere tra `"anonymous"` (non vengono mandati cookie, è necessario un header lato server) e `"use-credentials"` (manda i cookie, sono necessari 2 header lato server).
183183

184-
If we don't care about cookies, then `"anonymous"` is a way to go:
184+
Se non ci interessano i cookie allora `"anonymous"` è la scelta giusta:
185185

186186
```html run height=0
187187
<script>
@@ -192,15 +192,15 @@ window.onerror = function(message, url, line, col, errorObj) {
192192
<script *!*crossorigin="anonymous"*/!* src="https://cors.javascript.info/article/onload-onerror/crossorigin/error.js"></script>
193193
```
194194

195-
Now, assuming that the server provides `Access-Control-Allow-Origin` header, everything's fine. We have the full error report.
195+
Ora, supponendo che il server fornisca l'header `Access-Control-Allow-Origin`, riusciamo ad avere il report completo dell'errore.
196196

197-
## Summary
197+
## Riepilogo
198198

199-
Images `<img>`, external styles, scripts and other resources provide `load` and `error` events to track their loading:
199+
Immagini `<img>`, fogli di stile esterni, script e altre risorse forniscono gli eventi `load` e `error` per tracciare i loro caricamento:
200200

201-
- `load` triggers on a successful load,
202-
- `error` triggers on a failed load.
201+
- `load` si aziona se il caricamento va a buon fine,
202+
- `error` si azione se si verifica un errore durante il caricamento.
203203

204-
The only exception is `<iframe>`: for historical reasons it always triggers `load`, for any load completion, even if the page is not found.
204+
L'unica eccezione è `<iframe>`: per ragioni storiche scatta sempre l'evento `load`, per qualunque esito del caricamento, anche se la pagina non è stata trovata.
205205

206-
The `readystatechange` event also works for resources, but is rarely used, because `load/error` events are simpler.
206+
Possiamo monitorare il caricamento delle risorse anche tramite l'evento `readystatechange`, ma è poco utilizzato, perchè gli eventi `load/error` sono più semplici.

0 commit comments

Comments
 (0)