Skip to content
Merged
Changes from 1 commit
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
0e8551e
WIP
dbritto-dev Sep 29, 2020
33b4a34
WIP
dbritto-dev Sep 29, 2020
1b3ea1c
WIP
dbritto-dev Sep 29, 2020
d03b123
Minor changes
dbritto-dev Sep 29, 2020
63c99ed
Minor changes
dbritto-dev Sep 29, 2020
e4319a3
Minor changes
dbritto-dev Sep 29, 2020
64e55f6
numeracion en 117
joaquinelio Oct 1, 2020
75d2e1b
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
f602cc6
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
381618f
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
a2a972f
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
a48b291
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
c772da4
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
22a7032
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
59de9de
Minor changes
dbritto-dev Oct 1, 2020
1c213ea
Merge branch 'onload-onerror' of github.com:danilobrinu/es.javascript…
dbritto-dev Oct 1, 2020
67400ab
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
107e42c
Merge branch 'onload-onerror' of github.com:danilobrinu/es.javascript…
dbritto-dev Oct 1, 2020
d815df0
Minor changes
dbritto-dev Oct 1, 2020
a5a61d5
Minor changes
dbritto-dev Oct 1, 2020
6b8ffa5
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
22c3bb4
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
a040bad
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
6c7b486
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
c8e731a
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
465f59d
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
2c1c826
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
bcfbdc2
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
294e010
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
3a289ba
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
bc1d411
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
62027d7
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
f18878d
Update 2-ui/5-loading/03-onload-onerror/article.md
dbritto-dev Oct 1, 2020
a3c9011
Minor changes
dbritto-dev Oct 1, 2020
24bea0b
Merge branch 'onload-onerror' of github.com:danilobrinu/es.javascript…
dbritto-dev Oct 1, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
WIP
  • Loading branch information
dbritto-dev committed Sep 29, 2020
commit 0e8551ed253366610f8c60bdcb9dad0482340c4d
76 changes: 38 additions & 38 deletions 2-ui/5-loading/03-onload-onerror/article.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
# Resource loading: onload and onerror
# Carga de recursos: onload and onerror

The browser allows us to track the loading of external resources -- scripts, iframes, pictures and so on.
El navegador nos permite hacer seguimiento de la carga de recursos externos -- scripts, iframes, imagenes y más.
Comment thread
dbritto-dev marked this conversation as resolved.
Outdated

There are two events for it:
Hay dos eventos para eso:

- `onload` -- successful load,
- `onerror` -- an error occurred.
- `onload` -- cuando cargo exitosamente,
- `onerror` -- cuando un error ha ocurrido.

## Loading a script
## Cargando un script

Let's say we need to load a third-party script and call a function that resides there.
Digamos que tenemos que cargar un script de terceros y llamar una función que se encuentra dentro.

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

```js
let script = document.createElement('script');
Expand All @@ -20,68 +20,68 @@ script.src = "my.js";
document.head.append(script);
```

...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.
...pero como podemos ejecutar la función que esta dentro del script? Necesitamos esperar hasta que el script haya cargado, y solo después podemos llamarlo.
Comment thread
dbritto-dev marked this conversation as resolved.
Outdated

```smart
For our own scripts we could use [JavaScript modules](info:modules) here, but they are not widely adopted by third-party libraries.
Para nuestros scripts podemos usar [JavaScript modules](info:modules) esto, pero no esta adoptado ampliamente por bibliotecas de terceros.
Comment thread
dbritto-dev marked this conversation as resolved.
Outdated
```

### script.onload

The main helper is the `load` event. It triggers after the script was loaded and executed.
El evento `load` se ejecuta despues de que el script sea cargado y ejecutado.

For instance:
Por ejemplo:

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

// can load any script, from any domain
// podemos cargar cualquier script desde cualquier dominio
script.src = "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.3.0/lodash.js"
document.head.append(script);

*!*
script.onload = function() {
// the script creates a helper function "_"
alert(_); // the function is available
// el script crea una función de ayuda "_"
alert(_); // la función está disponible
};
*/!*
```

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

...And what if the loading failed? For instance, there's no such script (error 404) or the server is down (unavailable).
...y que si la carga falla? Por ejemplo: no hay tal script (error 404) en el servidor o el servidor esta caido (unavailable).
Comment thread
dbritto-dev marked this conversation as resolved.
Outdated

### script.onerror

Errors that occur during the loading of the script can be tracked in an `error` event.
Los errors que ocurren durante la carga de un script puede ser rastreados en el evento `error`.
Comment thread
dbritto-dev marked this conversation as resolved.
Outdated

For instance, let's request a script that doesn't exist:
Por ejemplo, hagamos una petición a un script que no existe:

```js run
let script = document.createElement('script');
script.src = "https://example.com/404.js"; // no such script
script.src = "https://example.com/404.js"; // no hay tal script
document.head.append(script);

*!*
script.onerror = function() {
alert("Error loading " + this.src); // Error loading https://example.com/404.js
alert("Error al cargar " + this.src); // Error al cargar https://example.com/404.js
};
*/!*
```

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.

```warn
Events `onload`/`onerror` track only the loading itself.
Los eventos `onload/onerror` rastrean solamente la carga de ellos mismos.

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

## Other resources

The `load` and `error` events also work for other resources, basically for any resource that has an external `src`.
Los eventos `load` y `error` también funcionan para otros recursos, basicamente para cualquier que tiene una externa `src`
Comment thread
dbritto-dev marked this conversation as resolved.
Outdated

For example:
Por ejemplo:

```js run
let img = document.createElement('img');
Expand All @@ -101,15 +101,15 @@ There are some notes though:
- Most resources start loading when they are added to the document. But `<img>` is an exception. It starts loading when it gets a src `(*)`.
- For `<iframe>`, the `iframe.onload` event triggers when the iframe loading finished, both for successful load and in case of an error.

That's for historical reasons.
Por históricas razones.
Comment thread
dbritto-dev marked this conversation as resolved.
Outdated

## Crossorigin policy
## Política de Crossorigin

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

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.

This rule also affects resources from other domains.
Esta regla también afecta a recursos de otros dominios.

If we're using a script from another domain, and there's an error in it, we can't get error details.

Expand All @@ -119,7 +119,7 @@ For example, let's take a script `error.js` that consists of a single (bad) func
noSuchFunction();
```

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

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

We can see a good error report, like this:
Podemos ver un buen reporte de error, como este:

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

Now let's load the same script from another domain:
Ahora carguemos el mismo script desde otro dominio:

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

The report is different, like this:
El reporte es diferente, como este:

```
Script error.
Expand All @@ -157,15 +157,15 @@ Script error.

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.

Why do we need error details?
¿Por qué necesitamos detalles de error?

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.

Similar cross-origin policy (CORS) is enforced for other types of resources as well.

**To allow cross-origin access, the `<script>` tag needs to have the `crossorigin` attribute, plus the remote server must provide special headers.**

There are three levels of cross-origin access:
Hay 3 niveles de acceso a cross-origin:

1. **No `crossorigin` attribute** -- access prohibited.
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.
Expand Down Expand Up @@ -196,11 +196,11 @@ Now, assuming that the server provides an `Access-Control-Allow-Origin` header,

## Summary

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

- `load` triggers on a successful load,
- `error` triggers on a failed load.
- `load` se ejecuta cuando la carga ha sido exitosa,
- `error` se ejecuta cuando una carga ha fallado.

The only exception is `<iframe>`: for historical reasons it always triggers `load`, for any load completion, even if the page is not found.
La única exception es el `<iframe>`: for razones historicas siempre dispara el evento `load`, incluso sino no encontró la página.
Comment thread
dbritto-dev marked this conversation as resolved.
Outdated

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