Skip to content

Commit 2ac0516

Browse files
author
Maksumi Murakami
authored
Merge pull request #393 from danilobrinu/onload-onerror
onload and onerror
2 parents 4885a21 + 24bea0b commit 2ac0516

File tree

3 files changed

+88
-88
lines changed

3 files changed

+88
-88
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+
El algoritmo:
3+
1. Crear una `img` para cada fuente.
4+
2. Agregar los eventos `onload/onerror` para cada imágen.
5+
3. Incrementar el contador cuando el evento `onload` o el evento `onerror` se dispare.
6+
4. Cuando el valor del contador es igual a la cantidad de fuentes, hemos terminado: `callback()`.

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

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

33
---
44

5-
# Load images with a callback
5+
# Cargando imágenes con una un función de retorno (`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, 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.
88

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:
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+
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.
1717

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`).**
1919

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:
2121

2222
```js
2323
function loaded() {
24-
alert("Images loaded")
24+
alert("Imágenes cargadas")
2525
}
2626

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+
En caso de un error, la función debería seguir asumiendo que la imágen ha sido "cargada".
3131

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.
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 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.
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+
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`.
Lines changed: 72 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -1,187 +1,187 @@
1-
# Resource loading: onload and onerror
1+
# Carga de recursos: onload y onerror
22

3-
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.
44

5-
There are two events for it:
5+
Hay dos eventos para eso:
66

7-
- `onload` -- successful load,
8-
- `onerror` -- an error occurred.
7+
- `onload` -- cuando cargó exitosamente,
8+
- `onerror` -- cuando un error ha ocurrido.
99

10-
## Loading a script
10+
## Cargando un script
1111

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.
1313

14-
We can load it dynamically, like this:
14+
Podemos cargarlo dinámicamente de esta manera:
1515

1616
```js
17-
let script = document.createElement('script');
17+
let script = document.createElement("script");
1818
script.src = "my.js";
1919

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+
...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.
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+
Para nuestros scripts podemos usar [JavaScript modules](info:modules) aquí, pero no está adoptado ampliamente por bibliotecas de terceros.
2727
```
2828

2929
### script.onload
3030

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.
3232

33-
For instance:
33+
Por ejemplo:
3434

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

38-
// can load any script, from any domain
38+
// podemos cargar cualquier script desde cualquier 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+
// el script crea una función de ayuda "_"
45+
alert(_); // la función está disponible
4646
};
4747
*/!*
4848
```
4949

50-
So in `onload` we can use script variables, run functions etc.
50+
Entonces en `onload` podemos usar variables, ejecutar funciones, etc.
5151

52-
...And what if the loading failed? For instance, there's no such script (error 404) or the server is down (unavailable).
52+
...¿y si la carga falla? Por ejemplo: no hay tal script (error 404) en el servidor o el servidor está caído (no diponible).
5353

5454
### script.onerror
5555

56-
Errors that occur during the loading of the script can be tracked in an `error` event.
56+
Los errores que ocurren durante la carga de un script pueden ser rastreados en el evento `error`.
5757

58-
For instance, let's request a script that doesn't exist:
58+
Por ejemplo, hagamos una petición a un script que no existe:
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"; // no hay tal script
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("Error al cargar " + this.src); // Error al cargar 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 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.
7373

7474
```warn
75-
Events `onload`/`onerror` track only the loading itself.
75+
Los eventos `onload/onerror` rastrean solamente la carga de ellos mismos.
7676
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`;
7878
```
7979

80-
## Other resources
80+
## Otros recursos
8181

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.
8383

84-
For example:
84+
Por ejemplo:
8585

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

90-
img.onload = function() {
90+
img.onload = function () {
9191
alert(`Image loaded, size ${img.width}x${img.height}`);
9292
};
9393

94-
img.onerror = function() {
94+
img.onerror = function () {
9595
alert("Error occurred while loading image");
9696
};
9797
```
9898

99-
There are some notes though:
99+
Sin embargo, hay algunas notas:
100100

101-
- 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.
103103

104-
That's for historical reasons.
104+
Esto es por razones históricas.
105105

106-
## Crossorigin policy
106+
## Política de origen cruzado
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+
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`.
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 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.
111111

112-
This rule also affects resources from other domains.
112+
Esta regla también afecta a recursos de otros dominios.
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+
Si usamos un script de otro dominio y tiene un error, no podemos obtener detalles del error.
115115

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).
117117
```js
118118
// 📁 error.js
119119
noSuchFunction();
120120
```
121121

122-
Now load it from the same site where it's located:
122+
Ahora cargalo desde el mismo sitio donde esta alojado:
123123

124124
```html run height=0
125125
<script>
126-
window.onerror = function(message, url, line, col, errorObj) {
127-
alert(`${message}\n${url}, ${line}:${col}`);
128-
};
126+
window.onerror = function (message, url, line, col, errorObj) {
127+
alert(`${message}\n${url}, ${line}:${col}`);
128+
};
129129
</script>
130130
<script src="/article/onload-onerror/crossorigin/error.js"></script>
131131
```
132132

133-
We can see a good error report, like this:
133+
Podemos ver un buen reporte de error, como este:
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+
Ahora carguemos el mismo script desde otro dominio:
141141

142142
```html run height=0
143143
<script>
144-
window.onerror = function(message, url, line, col, errorObj) {
145-
alert(`${message}\n${url}, ${line}:${col}`);
146-
};
144+
window.onerror = function (message, url, line, col, errorObj) {
145+
alert(`${message}\n${url}, ${line}:${col}`);
146+
};
147147
</script>
148148
<script src="https://cors.javascript.info/article/onload-onerror/crossorigin/error.js"></script>
149149
```
150150

151-
The report is different, like this:
151+
El reporte es diferente, como este:
152152

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

158-
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.
159159

160-
Why do we need error details?
160+
¿Por qué necesitamos detalles de error?
161161

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.
163163

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.
165165

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.**
167167

168-
There are three levels of cross-origin access:
168+
Hay 3 niveles de acceso de origen cruzado:
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. **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.
173173

174174
```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.
176176
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>.
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+
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.
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+
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).
183183

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:
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 an `Access-Control-Allow-Origin` header, everything's fine. We have the full error report.
195+
Ahora, asumiendo que el servidor brinda una cabecera `Access-Control-Allow-Origin`, todo está bien. Podemos tener el reporte completo del error.
196196

197-
## Summary
197+
## Resumen
198198

199-
Images `<img>`, external styles, scripts and other resources provide `load` and `error` events to track their loading:
199+
Las imágenes `<img>`, estilos externos, scripts y otros recursos proveen los eventos `load` y `error` para rastrear sus cargas:
200200

201-
- `load` triggers on a successful load,
202-
- `error` triggers on a failed load.
201+
- `load` se ejecuta cuando la carga ha sido exitosa,
202+
- `error` se ejecuta cuando una carga ha fallado.
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+
La única excepción es el `<iframe>`: por razones históricas siempre dispara el evento `load`, incluso si no encontró la página.
205205

206-
The `readystatechange` event also works for resources, but is rarely used, because `load/error` events are simpler.
206+
El evento `readystatechange` también funciona para recursos, pero es muy poco usado debido a que los eventos `load/error` son mas simples.

0 commit comments

Comments
 (0)