Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Scripts: async, defer#324

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
joaquinelio merged 26 commits intojavascript-tutorial:masterfromdbritto-dev:master
Jul 29, 2020
Merged
Changes fromall commits
Commits
Show all changes
26 commits
Select commitHold shift + click to select a range
110c128
Translate - Scripts: async, defer
dbritto-devJul 26, 2020
387d40f
Update article.md
dbritto-devJul 26, 2020
3392801
Update article.md
dbritto-devJul 26, 2020
04fe54f
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
f13cceb
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
344e441
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
bb5d273
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
5c441b2
Update article.md
dbritto-devJul 27, 2020
ad6a1fd
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
89185ba
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
6475b1c
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
f576eb0
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
656d411
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
91d7706
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
83e8176
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
844042d
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
e4aecf7
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
91b3af0
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
fe973fc
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
e925239
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
a0b8670
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
a2449ac
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
212eb55
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
60d5e05
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 2020
dea6a11
Update article.md
dbritto-devJul 27, 2020
b326102
Update 2-ui/5-loading/02-script-async-defer/article.md
dbritto-devJul 27, 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
134 changes: 67 additions & 67 deletions2-ui/5-loading/02-script-async-defer/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,150 +1,150 @@

# Scripts: async, defer

In modern websites,scriptsare often "heavier" thanHTML: their download size is larger, and processing time is also longer.
En los sitios web modernos losscriptssuelen ser más "pesados" que elHTML, el tamaño de la descarga es grande y el tiempo de procesamiento es mayor.

When the browser loadsHTMLand comes across a`<script>...</script>` tag, it can't continue building the DOM. It must execute the script right now. The same happens for external scripts `<script src="..."></script>`: the browser must wait until thescriptdownloads, execute it, and only after process the rest of the page.
Cuando el navegador carga elHTMLy se encuentra con una etiqueta`<script>...</script>`, no puede continuar construyendo el DOM ya que ahora debe ejecutar el script. Lo mismo sucede con los scriptsexternos`<script src="..."></script>`, el navegador tiene que esperar hasta que elscriptsea descargado para poder ejecutarlo y solo después procesa el resto de la página.

That leads to two important issues:
Esto nos lleva a dos importantes problemas:

1.Scripts can't seeDOMelements below them, so they can't add handlers etc.
2.If there's a bulkyscriptat the top of the page, it "blocks the page".Users can't see the page content till it downloads and runs:
1.Los scripts no pueden ver los elementos delDOMque se encuentran debajo de él por lo que no pueden agregar controladores de eventos, etc.
2.Si hay unscriptmuy pesado en la parte superior de la página, este "bloquea la página".Los usuarios no pueden ver el contenido de la página hasta que sea descargado y ejecutado.

```html run height=100
<p>...content before script...</p>
<p>...contenido previo al script...</p>

<script src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script>

<!--This isn'tvisibleuntil thescriptloads -->
<p>...content after script...</p>
<!--Esto no esvisiblehasta que elscriptsea cargado -->
<p>...contenido posterior al script...</p>
```

There are some workarounds to that. For instance, we can put ascriptat the bottom of the page. Then it can see elements above it, and it doesn't block the page content from showing:
Hay algunas soluciones para eso. Por ejemplo podemos poner elscripten la parte inferior de la página por lo que podrá ver los elementos sobre él y no bloqueará la visualización del contenido de la página.

```html
<body>
...all content is above the script...
...todo el contenido está arriba del script...

<script src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script>
</body>
```

But this solution is far from perfect. For example, the browser notices thescript (and can start downloading it) only after it downloaded the full HTML document. For long HTMLdocuments, that may be a noticeable delay.
Pero esta solución está lejos de ser perfecta. Por ejemplo el navegador solo se dará cuenta delscript (y podrá empezar a descargarlo) después de descargar todo el documento HTML. Para documentos HTMLextensos eso puede ser un retraso notable.

Such things are invisible for people using very fast connections, but many people in the world still have slowinternetspeeds and use a far-from-perfect mobile internetconnection.
Este tipo de cosas son imperceptibles para las personas que usan conexiones muy rápidas, pero muchas personas en el mundo todavía tienen velocidades deinternetlentas y utilizan una conexión de internetmóvil que esta lejos de ser perfecta.

Luckily, there are two`<script>`attributes that solve the problem for us: `defer`and `async`.
Afortunadamente hay dos atributos de`<script>`que resuelven ese problema para nosotros: `defer`y `async`.

## defer

The`defer`attribute tells the browser that it should go on working with the page, and load thescript "in background", then run the script when it loads.
El atributo`defer`indica al navegador que debe seguir trabajando en la página y cargar elscript "en segundo plano" para luego ejecutarlo cuando haya cargado.

Here's the same example as above, but with `defer`:
Aquí está el mismo ejemplo de arriba pero con `defer`:

```html run height=100
<p>...content before script...</p>
<p>...contenido previo script...</p>

<script defer src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script>

<!--visible immediately -->
<p>...content after script...</p>
<!--Inmediatamete visible -->
<p>...contenido posterior al script...</p>
```

-Scripts with`defer`never block the page.
-Scripts with`defer`always execute when theDOMis ready, but before`DOMContentLoaded` event.
-Los scripts con`defer`nunca bloquean la página.
-Los scripts con`defer`siempre se ejecutan cuando elDOMesta listo pero antes del evento`DOMContentLoaded`.

The following example demonstrates that:
Los siguientes ejemplos demuestran eso:

```html run height=100
<p>...content before scripts...</p>
<p>...contenido previo a los scripts...</p>

<script>
document.addEventListener('DOMContentLoaded', () => alert("DOMready after defer!")); // (2)
document.addEventListener('DOMContentLoaded', () => alert("¡DOMlisto después del defer!")); // (2)
</script>

<script defer src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script>

<p>...content after scripts...</p>
<p>...contenido posterior a los scripts...</p>
```

1.The page content shows up immediately.
2. `DOMContentLoaded`waits for the deferredscript. It only triggers when thescript `(2)`is downloaded and executed.
1.El contenido de la página se muestra inmediatamente.
2.El`DOMContentLoaded`espera por elscript diferido y solo lo se dispara cuando elscript `(2)`es descargado y ejecutado.

Deferred scriptskeep their relative order, just like regularscripts.
Los scriptsdiferidos mantienen su orden tal y cual losscripts regulares.

So, if we have a longscriptfirst, and then a smaller one, then the latter one waits.
Entonces si tenemos unscriptgrande primero y luego otro pequeño, el último espera.

```html
<script defer src="https://javascript.info/article/script-async-defer/long.js"></script>
<script defer src="https://javascript.info/article/script-async-defer/small.js"></script>
```

```smart header="The smallscriptdownloads first, runs second"
Browsers scan the page forscriptsand download them in parallel, to improve performance. So in the example above both scriptsdownload in parallel. The`small.js`probably makes it first.
```smart header="Elscriptpequeño se descarga primero y se ejecuta segundo"
Los navegadores analizan la página en busca descriptsy los descarga en paralelo para mejorar el rendimiento. Entonces en el ejemplo superior ambos scriptsse descargan en paralelo, el`small.js`probablemente lo haga primero.

But the specification requiresscriptsto execute in the document order, so it waits for`long.js`to execute.
Pero la especificación requiere que losscriptssean ejecutados en el orden en el que están en el documento, entonces espera por`long.js`para ejecutarlo.
```

```smart header="The`defer`attribute is only for externalscripts"
The`defer`attribute is ignored if the`<script>`tag has no `src`.
```smart header="El atributo`defer`es solo parascripts externos"
El atributo`defer`es ignorado si el`<script>`no tiene el atributo `src`.
```


## async

The`async`attribute means that ascriptis completely independent:
El atributo`async`significa que elscriptes completamente independiente:

-The page doesn't wait for async scripts, the contents are processed and displayed.
- `DOMContentLoaded`and async scriptsdon't wait for each other:
- `DOMContentLoaded`may happen both before an asyncscript(if an asyncscriptfinishes loading after the page is complete)
-...or after an async script(if an asyncscriptis short or was in HTTP-cache)
-Other scriptsdon't wait for `async` scripts, and `async`scriptsdon't wait for them.
-La página no espera a los scripts asincrónicos por lo que el contenido de la página se procesa y se muestra.
-El evento`DOMContentLoaded`y los scriptsasincrónicos no se esperan entre sí:
-El evento`DOMContentLoaded`puede suceder antes que unscriptasincrónico (si unscriptasincrónico termina de cargar una vez la página está completa)
-o después de un scriptasincrónico (si talscriptasincrónico es pequeño o está encache)
-Otros scriptsno esperan a los scripts asincrónicos y losscriptsasincrónicos no esperan por ellos.


So, if we have several `async` scripts, they may execute in any order. Whatever loads first -- runs first:
Entonces si tenemos muchos scripts asincrónicos estos pueden ser ejecutados en cualquier orden, cualquiera que cargue primero se ejecutará primero.

```html run height=100
<p>...content before scripts...</p>
<p>...contenido previo a los scripts...</p>

<script>
document.addEventListener('DOMContentLoaded', () => alert("DOMready!"));
document.addEventListener('DOMContentLoaded', () => alert("¡DOMlisto!"));
</script>

<script async src="https://javascript.info/article/script-async-defer/long.js"></script>
<script async src="https://javascript.info/article/script-async-defer/small.js"></script>

<p>...content after scripts...</p>
<p>...contenido posterior a los scripts...</p>
```

1.The page content shows up immediately: `async`doesn't block it.
2. `DOMContentLoaded`may happen both before and after `async`, noguarantees here.
3.Async scriptsdon't wait for each other. A smallerscript `small.js`goes second, but probably loads before`long.js`, so runs first. That's called a"load-first" order.
1.El contenido de la página se muestra inmediatamente: `async`no lo bloquea.
2.El evento`DOMContentLoaded`puede suceder antes o después de `async`, nohay garantías aquí.
3.Los scriptsasincrónicos no esperan por el otro. Unscriptpequeño`small.js`va segundo pero probablemente cargue antes que`long.js` entonces se ejecutará primero. A eso lo llamamos"load-first order".

Async scriptsare great when we integrate an independent third-party script into the page: counters, ads and so on, as they don't depend on ourscripts, and our scriptsshouldn't wait for them:
Los scriptsasincrónicos son excelentes cuando incluimos scripts de terceros (contadores, anuncios, etc) en la página debido a que ellos no dependen de nuestrosscripts y nuestros scriptsno deberían esperar por ellos.

```html
<!-- Google Analytics is usually added like this -->
<script async src="https://google-analytics.com/analytics.js"></script>
```


##Dynamic scripts
##Scripts dinámicos

We can also add ascriptdynamically using #"d46fde5bdf9f1bfe30be3edd2854f75df400bcb49deba7405dab126d900e2eb9">También podemos agregar unscriptdinámicamente usando #"d46fde5bdf9f1bfe30be3edd2854f75df400bcb49deba7405dab126d900e2eb9">
```js run
let script = document.createElement('script');
script.src = "/article/script-async-defer/long.js";
document.body.append(script); // (*)
```

The scriptstarts loading as soon as it's appended to the document `(*)`.
El scriptcomienza a cargar tan pronto como es agregado al documento `(*)`.

**Dynamic scriptsbehave as "async" by default.**
**Los scriptsdinámicos se comportan como `async` por defecto**

That is:
-They don't wait for anything, nothing waits for them.
-The scriptthat loads first -- runs first ("load-first" order).
Esto es:
-Ellos no esperan a nadie y nadie espera por ellos.
-El scriptque carga primero se ejecuta primero (`load-first order`)


```js run
Expand All@@ -158,7 +158,7 @@ script.async = false;
document.body.append(script);
```

For example, here we add twoscripts. Without`script.async=false`they would execute inload-first order (the `small.js`probably first).But with that flag the order is "as in thedocument":
Por ejemplo, aquí agregamos dosscripts sin el`script.async=false`por lo que deberían ejecutarse en `load-first order` (el `small.js`probablemente primero).Pero con esa bandera el orden es `document order`.


```js run
Expand All@@ -169,29 +169,29 @@ function loadScript(src) {
document.body.append(script);
}

// long.jsruns first because of async=false
// long.jsse ejecuta primero a causa del async=false
loadScript("/article/script-async-defer/long.js");
loadScript("/article/script-async-defer/small.js");
```


##Summary
##Resumen

Both `async`and `defer` have one common thing: downloading of suchscriptsdoesn't block page rendering. So the user can read page content and get acquainted with the page immediately.
Ambos, `async`y `defer`, tienen algo en común: la descarga de talesscriptsno bloquean el renderizado de la página. Por lo cual el usuario puede leer el contenido de la página y familiarizarse con la página inmediatamente.

But there are also essential differences between them:
Pero hay algunas diferencias esenciales entre ellos:

| |Order | `DOMContentLoaded` |
| |Orden | `DOMContentLoaded` |
|---------|---------|---------|
| `async` | *Load-first order*.Their document order doesn't matter -- which loads first | Irrelevant. May load and execute while the document has not yet been fully downloaded. That happens if scripts are small or cached, and the document is long enough. |
| `defer` | *Document order* (as they go in the document). |Execute after the document is loaded and parsed (they wait if needed), right before `DOMContentLoaded`. |
| `async` | *Load-first order*.El orden del documento no importa. ¿cual script carga primero? | Tal vez cargue y ejecute mientras el documento no ha sido completamente descargado, eso puede pasar si el script es pequeño o está en cache y el documento es suficientemente extenso. |
| `defer` | *Document order* (como va en el documento). |Ejecuta después de que el documento es cargado y analizado (espera si es necesario) |

```warn header="Page withoutscriptsshould be usable"
Please note that if you're using`defer`, then the page isvisible*before* thescriptloads.
```warn header="La página sinscriptsdebe ser utilizable"
Por favor ten en cuenta que si estas usando`defer` la página esvisibleantes de que elscriptsea cargado.

So the user may read the page, but some graphical components are probably not ready yet.
Por lo que el usuario tal vez pueda leer la página, pero algunos componentes gráficos probablemente no estén listos.

There should be "loading" indications in the proper places, and disabled buttons should show as such, so the user can clearly see what's ready and what's not.
Debería haber algunas señales de "cargando" en lugares apropiados y los botones deshabilitados deberían ser mostrados como tal para que el usuario pueda ver claramente qué está listo y qué no.
```

In practice, `defer`is used for scriptsthat need the whole DOMand/or their relative execution order is important. And`async`is used for independentscripts, like counters or ads. And their relative execution order does not matter.
En la práctica, `defer`es usado para scriptsque necesitan todo el DOMy/o el orden de ejecución es importante. Y`async`es usado parascripts independientes como contadores y anuncios donde el orden de ejecución no importa.

[8]ページ先頭

©2009-2025 Movatter.jp