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
Copy file name to clipboardExpand all lines: 2-ui/5-loading/03-onload-onerror/1-load-img-callback/task.md
+10-10Lines changed: 10 additions & 10 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2,22 +2,22 @@ importance: 4
2
2
3
3
---
4
4
5
-
# Load images with a callback
5
+
# Caricare immagini con una callback
6
6
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.
8
8
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:
10
10
11
11
```js
12
12
let img =document.createElement('img');
13
13
img.src='my.jpg';
14
14
```
15
15
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.
17
17
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`.**
19
19
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:
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"
31
31
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.
33
33
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.
35
35
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`.
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.
4
4
5
-
There are two events for it:
5
+
Esistono 2 eventi per tracciare il caricamento:
6
6
7
-
-`onload` -- successful load,
8
-
-`onerror` -- an error occurred.
7
+
-`onload` -- caricato con success,
8
+
-`onerror` -- si è verificato un errore.
9
9
10
-
## Loading a script
10
+
## Caricamento di uno script
11
11
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.
13
13
14
-
We can load it dynamically, like this:
14
+
Possiamo caricarlo dinamicamente, in questo modo:
15
15
16
16
```js
17
17
let script =document.createElement('script');
@@ -20,106 +20,106 @@ script.src = "my.js";
20
20
document.head.append(script);
21
21
```
22
22
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.
24
24
25
25
```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.
27
27
```
28
28
29
29
### script.onload
30
30
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.
32
32
33
-
For instance:
33
+
Per esempio:
34
34
35
35
```js run untrusted
36
36
let script =document.createElement('script');
37
37
38
-
//can load any script, from any domain
38
+
//si può caricare qualunque script, da qualunque dominio
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.
51
51
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).
53
53
54
54
### script.onerror
55
55
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`.
57
57
58
-
For instance, let's request a script that doesn't exist:
58
+
Per esempio, proviamo a richiedere uno script che non esiste:
59
59
60
60
```js run
61
61
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
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.
73
73
74
74
```warn
75
-
Events `onload`/`onerror` track only the loading itself.
75
+
Gli eventi `onload`/`onerror` tracciano solo il caricamento stesso.
76
76
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`.
78
78
```
79
79
80
-
## Other resources
80
+
## Altre risorse
81
81
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.
alert("Si è verificato un errore durante il caricamento dell'immagine");
96
96
};
97
97
```
98
98
99
-
There are some notes though:
99
+
Ci sono alcune note però:
100
100
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.
103
103
104
-
That's for historical reasons.
104
+
Questo avviene per ragioni storiche.
105
105
106
106
## Crossorigin policy
107
107
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`.
109
109
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.
111
111
112
-
This rule also affects resources from other domains.
112
+
Questa regola interessa anche le risorse di altri domini.
113
113
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.
115
115
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):
117
117
```js
118
118
// 📁 error.js
119
119
noSuchFunction();
120
120
```
121
121
122
-
Now load it from the same site where it's located:
122
+
Ora caricatela dallo stesso sito su cui è situato lo script:
Il report di errore è diverso rispetto a quello precedente, come questo:
152
152
153
153
```
154
154
Script error.
155
155
, 0:0
156
156
```
157
157
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.
159
159
160
-
Why do we need error details?
160
+
Perchè abbiamo bisogno dei dettagli di errore?
161
161
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.
163
163
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.
165
165
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.**
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.
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.
173
173
174
174
```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.
176
176
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>.
178
178
```
179
179
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.
181
181
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).
183
183
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:
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.
196
196
197
-
## Summary
197
+
## Riepilogo
198
198
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:
200
200
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.
203
203
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.
205
205
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