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
+11-11Lines changed: 11 additions & 11 deletions
Original file line number
Diff line number
Diff line change
@@ -2,35 +2,35 @@ importance: 4
2
2
3
3
---
4
4
5
-
# Load images with a callback
5
+
# Cargando imágenes con una un función de retorno (`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, las imágenes son cargadas cuando son creadas. Entonces, cuando nosotros agregamos`<img>`a la página el usuario no ve la imágen inmediatamente. El navegador necesita cargarlo primero.
8
8
9
-
To show an image immediately, we can create it "in advance", like this:
9
+
Para mostrar una imágen inmediatamente, podemos crearlo "en avance", como esto:
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
+
El navegador comienza a cargar la imágen y lo guarda en el cache. Después cuando la misma imágen aparece en el documento (no importa cómo) la muestra inmediatamente.
17
17
18
-
**Create a function`preloadImages(sources, callback)`that loads all images from the array `sources` and, when ready, runs `callback`.**
18
+
**Crear una función`preloadImages(sources, callback)`que cargue todas las imágenes desde una lista de fuentes (`sources`) y, cuando esten listas, ejecutar la función de retorno (`callback`).**
19
19
20
-
For instance, this will show an `alert` after the images are loaded:
20
+
Por ejemplo: esto puede mostrar una alerta (`alert`) después de que la imágen sea cargada:
In case of an error, the function should still assume the picture "loaded".
30
+
En caso de un error, la función debería seguir asumiendo que la imágen ha sido "cargada".
31
31
32
-
In other words, the `callback` is executed when all images are either loaded or errored out.
32
+
En otras palabras, la función de retorno (`callback`) es ejecutada cuando todas las imágenes han sido cargadas o no.
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 función es útil, por ejemplo, cuando planeamos mostrar una galería con muchas imágenes desplazables y estar seguros que todas las imágenes estan cargadas.
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
+
En el documento fuente puedes encontrar enlaces para probar imágenes y también el codigo para verificar si han sido cargadas o no. Debería devolver`300`.
The browser allows us to track the loading of external resources -- scripts, iframes, pictures and so on.
3
+
El navegador nos permite hacer seguimiento de la carga de recursos externos: scripts, iframes, imagenes y más.
4
4
5
-
There are two events for it:
5
+
Hay dos eventos para eso:
6
6
7
-
-`onload` -- successful load,
8
-
-`onerror` -- an error occurred.
7
+
-`onload` -- cuando cargó exitosamente,
8
+
-`onerror` -- cuando un error ha ocurrido.
9
9
10
-
## Loading a script
10
+
## Cargando un script
11
11
12
-
Let's say we need to load a third-party script and call a function that resides there.
12
+
Digamos que tenemos que cargar un script de terceros y llamar una función que se encuentra dentro.
13
13
14
-
We can load it dynamically, like this:
14
+
Podemos cargarlo dinámicamente de esta manera:
15
15
16
16
```js
17
-
let script =document.createElement('script');
17
+
let script =document.createElement("script");
18
18
script.src="my.js";
19
19
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
+
...pero ¿cómo podemos ejecutar la función que esta dentro del script? Necesitamos esperar hasta que el script haya cargado, y solo después podemos llamarlo.
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
+
Para nuestros scripts podemos usar [JavaScript modules](info:modules) aquí, pero no está adoptado ampliamente por bibliotecas de terceros.
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
+
El evento `load`se dispara después de que script sea cargado y ejecutado.
32
32
33
-
For instance:
33
+
Por ejemplo:
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
+
//podemos cargar cualquier script desde cualquier dominio
alert("Error al cargar "+this.src); // Error al cargar https://example.com/404.js
68
68
};
69
69
*/!*
70
70
```
71
71
72
-
Please note that we can't get HTTP error details here. We don't know if it was an error 404 or 500 or something else. Just that the loading failed.
72
+
Por favor nota que como no podemos obtener detalles del error HTTP aquí, no podemos saber if fue un error 404 o algo diferente. Solo el error de carga.
73
73
74
74
```warn
75
-
Events `onload`/`onerror` track only the loading itself.
75
+
Los eventos `onload/onerror` rastrean solamente la carga de ellos mismos.
76
76
77
-
Errors that may occur during script processing and execution are out of scope for these events. That is: if a script loaded successfully, then `onload` triggers, even if it has programming errors in it. To track script errors, one can use `window.onerror` global handler.
77
+
Los errores que pueden ocurrir durante el procesamiento y ejecución están fuera del alcance para esos eventos. Eso es: si un script es cargado de manera exitosa, incluso si tiene errores de programación adentro, el evento `onload` se dispara. Para rastrear los errores del script un puede usar el manejador global `window.onerror`;
78
78
```
79
79
80
-
## Other resources
80
+
## Otros recursos
81
81
82
-
The `load`and`error`events also work for other resources, basically for any resource that has an external `src`.
82
+
Los eventos `load`y`error`también funcionan para otros recursos, básicamente para cualquiera que tenga una `src` externa.
-Most resources start loading when they are added to the document. But`<img>`is an exception. It starts loading when it gets a 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 mayoría de recursos empiezan a cargarse cuando son agregados al documento. Pero`<img>`es una excepción, comienza la carga cuando obtiene una fuente ".src"`(*)`.
102
+
-Para`<iframe>`, el evento `iframe.onload`se dispara cuando el iframe ha terminado de cargar, tanto para una carga exitosa como en caso de un error.
103
103
104
-
That's for historical reasons.
104
+
Esto es por razones históricas.
105
105
106
-
## Crossorigin policy
106
+
## Política de origen cruzado
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
+
Hay una regla: los scripts de un sitio no pueden acceder al contenido de otro sitio. Por ejemplo: un script de`https://facebook.com`no puede leer la bandeja de correos del usuario en`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 with no access to each other.
110
+
O para ser más precisos, un origen (el trío dominio/puerto/protocolo) no puede acceder al contenido de otro. Entonces, incluso si tenemos un sub-dominio o solo un puerto distinto, son considerados origenes diferentes sin acceso al otro.
111
111
112
-
This rule also affects resources from other domains.
112
+
Esta regla también afecta a recursos de otros dominios.
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
+
Si usamos un script de otro dominio y tiene un error, no podemos obtener detalles del error.
115
115
116
-
For example, let's take a script `error.js`that consists of a single (bad) function call:
116
+
Por ejemplo, tomemos un script `error.js`que consta de un única llamada a una función (con errores).
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
+
Ahora cargalo desde el mismo sitio donde esta alojado:
Details may vary depending on the browser, but the idea is the same: any information about the internals of a script, including error stack traces, is hidden. Exactly because it's from another domain.
158
+
Los detalles pueden variar dependiendo del navegador, pero la idea es la misma: cualquier información sobre las partes internas de un script, incluyendo el rastreo de la pila de errores, se oculta. Exactamente porque es de otro dominio.
159
159
160
-
Why do we need error details?
160
+
¿Por qué necesitamos detalles de error?
161
161
162
-
There are many services (and we can build our own) that listen for 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 not much information about errors in it, as we've just seen.
162
+
Hay muchos servicios (y podemos construir uno nuestro) que escuchan los errores globales usando`window.onerror`, guardan los errores y proveen una interfaz para acceder a ellos y analizarlos. Eso es grandioso ya que podemos ver los errores originales ocasionados por nuestros usuarios. Pero si el script viene desde otro origen no hay mucha información sobre los errores como acabamos de ver.
163
163
164
-
Similar cross-origin policy (CORS) is enforced for other types of resources as well.
164
+
También se aplican políticas similares de origen cruzado (CORS) a otros tipos de recursos.
165
165
166
-
**To allow cross-origin access, the `<script>`tag needs to have the `crossorigin` attribute, plus the remote server must provide special headers.**
166
+
**Para permitir el accesso de origen cruzado, la etiqueta `<script>`necesita tener el atributo `crossorigin`, además el servidor remoto debe proporcionar cabeceras especiales.**
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.**Sin el atributo `crossorigin`** -- acceso prohibido.
171
+
2.**`crossorigin="anonymous"`** -- acceso permitido si el servidor responde con la cabecera`Access-Control-Allow-Origin`con`*`o nuestro origen. El navegador no envía la información de la autorización y cookies al servidor remoto.
172
+
3.**`crossorigin="use-credentials"`** -- acceso permitido si el servidor envia de vuelta la cabecera `Access-Control-Allow-Origin`con nuestro origen y`Access-Control-Allow-Credentials: true`. El navegador envía la información de la autorización y las cookies al servidor remoto.
173
173
174
174
```smart
175
-
You can read more about cross-origin access in the chapter <info:fetch-crossorigin>. It describes the `fetch` method for network requests, but the policy is exactly the same.
175
+
Puedes leer más sobre accesos de origen cruzado en el capítulo <info:fetch-crossorigin>. Este describe el método `fetch` para requerimientos de red, pero la política es exactamente la misma.
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
+
Cosas como las "cookies" estan fuera de nuestro alcance, pero podemos leer sobre ellas en <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
+
En nuetro caso no teníamos ningún atributo de origen cruzado (`cross-origin`). Por lo que se prohibió el acceso de origen cruzado. Vamos a agregarlo.
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
+
Podemos elegir entre `"anonymous"` (no se envian las cookies, una sola cabecera esa necesaria en el lado del servidor) y`"use-credentials"` (envias las cookies, dos cabeceras son necesarias en el lado del servidor).
183
183
184
-
If we don't care about cookies, then`"anonymous"`is the way to go:
184
+
Si no nos importan las `cookies`, entonces`"anonymous"`es el camino a seguir:
0 commit comments