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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
In modern websites,scriptsare often "heavier" thanHTML:theirdownloadsize is larger, and processing time is also longer.
Em sites modernos, osscriptsgeralmente são "mais pesados" do que oHTML:seu tamanho paradownloadé maior e o tempo de processamento também é maior.
When the browser loadsHTMLand comes across a `<script>...</script>` tag, it can't continue building theDOM.It must execute the scriptright now. The same happens for externalscripts `<script src="..."></script>`:the browser must wait for the script to download, execute the downloadedscript, and only then can it process the rest of the page.
Quando o navegador carrega oHTMLe encontra uma tag `<script>...</script>`, ele não pode continuar construindo oDOM.Ele deve executar o scriptno momento exato que o encontra. O mesmo acontece comscriptsexternos`<script src="..."></script>`:o navegador deve aguardar o download do script, executar oscript baixado e só então pode processar o resto da página.
That leads to two important issues:
Isso nos leva a duas questões importantes:
1.Scripts can't see DOM elements 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.Os scripts não conseguem ver os elementos do DOM abaixo deles, então não conseguem manipular eventos, etc.
2.Se houver umscriptvolumoso no topo da página, ele vai "bloquear a página".Os usuários não podem ver o conteúdo da página até que o script seja baixado e executado.
<!--Isso não se torna visível até que oscriptcarregue -->
<p>...conteúdo depois do 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:
Existem algumas soluções alternativas para esses problemas. Por exemplo, podemos colocar umscriptno final da página. Assim, ele pode ver os elementos acima dele e consequentemente, não bloqueia a exibição do conteúdo da página:
But this solution is far from perfect. For example, the browser notices the script (and can start downloading it) only after it downloaded the full HTMLdocument. For long HTMLdocuments, that may be a noticeable delay.
Mas essa solução está longe de ser perfeita. Por exemplo, o navegador percebe o script (e pode começar a baixá-lo) somente depois de baixar o documento HTMLpor completo. Para documentos HTMLlongos, isso pode ser um atraso perceptível para o usuário.
Such things are invisible for people using very fast connections, but many people in the world still have slow internet speeds and use a far-from-perfect mobileinternetconnection.
Essas coisas são invisíveis para pessoas que usam conexões de internet muito rápidas, mas muitas pessoas no mundo ainda têm velocidades lentas e usam uma conexão deinternetmóvel longe de ser perfeita.
Luckily, there are two `<script>`attributes that solve the problem for us: `defer`and `async`.
Felizmente, existem dois atributos `<script>`que resolvem o problema para nós: `defer`e `async`.
## defer
The`defer`attribute tells the browser not to wait for thescript.Instead, the browser will continue to process the HTML, buildDOM.The scriptloads "in the background", and then runs when theDOMis fully built.
O atributo`defer`diz ao navegador para não esperar peloscript.Em vez disso, o navegador continuará processando o HTML e criando aDOM.O scriptcarrega "em segundo plano" e, em seguida, é executado quando aDOMestá totalmente criada.
Here's the same example as above, but with `defer`:
Aqui está o mesmo exemplo acima, mas utilizando o `defer`:
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 finishes first.
Os navegadores examinam a página em busca descriptse os baixam em paralelo para melhorar o desempenho. Portanto, no exemplo acima, os dois scriptssão baixados em paralelo. O `small.js`provavelmente terminará primeiro.
...But the`defer` attribute, besides telling the browser "not to block",ensures that the relative order is kept. So even though`small.js`loads first, it still waits and runs after`long.js` executes.
... Mas o atributo`defer`, além de dizer ao navegador "não bloquear",garante que a ordem relativa seja mantida. Portanto, embora`small.js`carregue primeiro, ele ainda espera e executa após a execução de`long.js`.
That may be important for cases when we need to load aJavaScriptlibrary and then a scriptthat depends on it.
Isso pode ser importante para os casos em que precisamos carregar uma bibliotecaJavaScripte, em seguida, um scriptque depende dela.
```smart header="The`defer`attribute is only for externalscripts"
The`defer`attribute is ignored if the `<script>`tag has no `src`.
```smart header="O atributo`defer`é apenas parascripts externos"
O atributo`defer`é ignorado se a tag `<script>`não possui o atributo `src`.
```
## async
The`async`attribute is somewhat like `defer`.It also makes the script non-blocking. But it has important differences in the behavior.
O atributo`async`é parecido com o `defer`.Ele também não bloqueia a página, mas tem diferenças importantes no seu comportamento.
The`async`attribute means that ascriptis completely independent:
O atributo`async`significa que umscripté completamente independente:
-Other scriptsdon't wait for`async` scripts, and`async`scripts don't wait for them.
- `DOMContentLoaded`and async scriptsdon't wait for each other:
- `DOMContentLoaded`may happen both before an asyncscript(if anasync script finishes loading after the page is complete)
- ...or after an async script(if anasync script is short or was in HTTP-cache)
-O navegador não bloqueia em scripts`async`(como `defer`).
-Outros scriptsnão esperam por scripts`async`, e scripts`async`não esperam por eles.
-O evento`DOMContentLoaded`e os scripts`async` não esperam um pelo outro:
- `DOMContentLoaded`pode acontecer antes de umscript`async` (se um script `async` terminar de carregar depois que a página for concluída)
- ... ou após um script`async` (se um script `async` for curto ou estiver em cache HTTP)
In other words,`async`scripts load in the background and run when ready. The DOMand other scriptsdon't wait for them, and they don't wait for anything. A fully independent script that runs when loaded. As simple, as it can get, right?
Em outras palavras, os scripts`async`são carregados em segundo plano e executados quando prontos. O DOMe outros scriptsnão esperam por eles e não esperam por nada. Um script totalmente independente que é executado quando carregado. Tão simples quanto parece, não é mesmo?
Here's an example similar to what we've seen with`defer`:two scripts `long.js`and `small.js`,but now with `async`instead of `defer`.
Aqui está um exemplo parecido ao que vimos com o`defer`:dois scripts `long.js`e `small.js`,mas agora com `async`em vez de `defer`.
They don't wait for each other. Whatever loads first (probably `small.js`) -- runs first:
Eles não esperam um pelo outro. Qualquer um que carregue primeiro (provavelmente `small.js`) - é executado primeiro:
-The page content shows up immediately: `async`doesn't block it.
- `DOMContentLoaded`may happen both before and after `async`,no guarantees here.
-A smallerscript `small.js`goes second, but probably loads before`long.js`,so `small.js`runs first. Although, it might be that`long.js`loads first, if cached, then it runs first. In other words, async scriptsrun in the "load-first" order.
-O conteúdo da página aparece imediatamente: `async`não o bloqueia.
- `DOMContentLoaded`pode acontecer antes e depois de `async`,sem garantias aqui.
-Umscriptmenor`small.js`está em segundo lugar, mas provavelmente carrega antes de`long.js`,então `small.js`é executado primeiro. Embora, pode ser que`long.js`carregue primeiro, se armazenado em cache, ele executa primeiro. Em outras palavras, os scripts`async` são executados na ordem que "carregar primeiro".
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 our scripts,and our scriptsshouldn't wait for them:
Os scripts`async` são ótimos quando integramos um script independente de terceiros na página: contadores, anúncios e assim por diante, pois eles não dependem de nossos scripts,e nossos scriptsnão devem esperar por eles:
```html
<!-- Google Analyticsis usually added like this -->
<!--OGoogle Analyticsgeralmente é adicionado assim -->
The scriptstarts loading as soon as it's appended to the document `(*)`.
O scriptcomeça a carregar assim que é anexado ao documento `(*)`.
**Dynamic scriptsbehave as"async"by default.**
**Os scriptsdinâmicos se comportam como"async"por padrão.**
That is:
-They don't wait for anything, nothing waits for them.
-The scriptthat loads first --runs first ("load-first" order).
Resumindo:
-Eles não esperam nada, nada os espera.
-O scriptque carrega primeiro --é executado primeiro (ordem que "carregar primeiro").
This can be changed if we explicitly set`script.async=false`.Then scripts will be executed in the document order, just like `defer`.
Isso pode ser alterado se definirmos explicitamente`script.async=false`.Em seguida, os scripts serão executados na ordem do documento, assim como `defer`.
In this example,`loadScript(src)`function adds ascriptand also sets `async`to `false`.
Neste exemplo, a função`loadScript(src)`adiciona umscripte também define `async`como `false`.
So `long.js`always runs first (as it's added first):
Portanto, `long.js`sempre executa primeiro (como é adicionado primeiro):
Without `script.async=false`, scriptswould execute in default, load-first order (the `small.js`probably first).
Sem `script.async=false`,osscriptsseriam executados na ordem padrão de carregamento primeiro (o `small.js`provavelmente primeiro).
Again, as with the`defer`,the order matters if we'd like to load a library and then anotherscriptthat depends on it.
Novamente, como acontece com o`defer`,a ordem é importante se quisermos carregar uma biblioteca e depois outroscriptque dependa dela.
##Summary
##Resumo
Both `async`and `defer`have one common thing: downloading of such scriptsdoesn't block page rendering. So the user can read page content and get acquainted with the page immediately.
Ambos `async`e `defer`têm uma coisa em comum: o download dos scriptsnão bloqueia a renderização da página. Assim, o usuário pode ler o conteúdo da página e familiarizar-se com a página imediatamente.
But there are also essential differences between them:
Mas também existem diferenças essenciais entre eles:
| |Order | `DOMContentLoaded` |
| |Ordem | `DOMContentLoaded` |
|---------|---------|---------|
| `async` | *Load-first order*.Their document order doesn't matter -- which loads first runs first|Irrelevant. May load and execute while the document has not yet been fully downloaded. That happens ifscriptsare 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` | *Ordem do que carregar primeiro*.A ordem dos documentos não importa - o que carrega primeiro é executado primeiro|Irrelevante. Pode carregar e executar enquanto o documento ainda não foi totalmente baixado. Isso acontece se osscriptsforem pequenos ou armazenados em cache e o documento for longo o suficiente. |
| `defer` | *Ordem do documento* (conforme estão no documento). |Executa depois que o documento é carregado e transformado (eles esperam se for preciso),logo antes do `DOMContentLoaded`. |
In practice, `defer`is used for scriptsthat need the wholeDOMand/or their relative execution order is important.
Na prática, `defer`é usado para scriptsque precisam de todo oDOMe/ou sua ordem de execução relativa é importante.
And`async`is used for independentscripts, like counters or ads. And their relative execution order does not matter.
E`async`é usado parascripts independentes, como contadores ou anúncios. E sua ordem de execução relativa não importa.
```warn header="Page withoutscriptsshould be usable"
Please note: if you're using`defer`or `async`,then user will see the page *before* the scriptloads.
```warn header="A página semscriptsdeve ser utilizável"
Atenção: se você estiver usando`defer`ou `async`,o usuário verá a página *antes* do scriptcarregar.
In such case, some graphical components are probably not initialized yet.
Nesse caso, alguns componentes podem não ter inicializado na tela ainda.
Don't forget to put "loading" indication and disable buttons that aren't functional yet. Let the user clearly see what he can do on the page, and what's still getting ready.
```
Não se esqueça de indicar que eles estão "carregando" e desabilitar os botões que ainda não devem funcionar. Deixe o usuário ver claramente o que ele pode fazer na página e o que ainda está sendo preparado.
```
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.