diff --git a/2-ui/5-loading/02-script-async-defer/article.md b/2-ui/5-loading/02-script-async-defer/article.md index f97c000d6..36434aa50 100644 --- a/2-ui/5-loading/02-script-async-defer/article.md +++ b/2-ui/5-loading/02-script-async-defer/article.md @@ -1,147 +1,147 @@ # Scripts: async, defer -In modern websites, scripts are often "heavier" than HTML: their download size is larger, and processing time is also longer. +Em sites modernos, os scripts geralmente são "mais pesados" do que o HTML: seu tamanho para download é maior e o tempo de processamento também é maior. -When the browser loads HTML and comes across a `` tag, it can't continue building the DOM. It must execute the script right now. The same happens for external scripts ``: the browser must wait for the script to download, execute the downloaded script, and only then can it process the rest of the page. +Quando o navegador carrega o HTML e encontra uma tag ``, ele não pode continuar construindo o DOM. Ele deve executar o script no momento exato que o encontra. O mesmo acontece com scripts externos ``: o navegador deve aguardar o download do script, executar o script 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 bulky script at 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 um script volumoso 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. ```html run height=100 -

...content before script...

+

...conteúdo antes do script...

- -

...content after script...

+ +

...conteúdo depois do script...

``` -There are some workarounds to that. For instance, we can put a script at 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 um script no 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: ```html - ...all content is above the script... + ...todo o conteúdo acima do script... ``` -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 HTML document. For long HTML documents, 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 HTML por completo. Para documentos HTML longos, 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 mobile internet connection. +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 de internet móvel longe de ser perfeita. -Luckily, there are two ` - -

...content after script...

+ +

...conteúdo depois do script...

``` -In other words: +Em outras palavras: -- Scripts with `defer` never block the page. -- Scripts with `defer` always execute when the DOM is ready (but before `DOMContentLoaded` event). +- Scripts com `defer` nunca bloqueiam a página. +- Scripts com `defer` sempre são executados quando a DOM está pronto (mas antes do evento `DOMContentLoaded`). -The following example demonstrates the second part: +O exemplo a seguir demonstra a segunda parte: ```html run height=100 -

...content before scripts...

+

...conteúdo antes do script...

-

...content after scripts...

+

...conteúdo depois do script...

``` -1. The page content shows up immediately. -2. `DOMContentLoaded` event handler waits for the deferred script. It only triggers when the script is downloaded and executed. +1. O conteúdo da página aparece imediatamente. +2. O manipulador de eventos `DOMContentLoaded` espera pelo script com a tag defer. O evento é disparado só quando o script é baixado e executado. -**Deferred scripts keep their relative order, just like regular scripts.** +**Os scripts com a tag defer mantêm sua ordem relativa, assim como os scripts normais.** +Digamos que temos dois scripts com a tag defer: o `long.js` e o `small.js`: -Let's say, we have two deferred scripts: the `long.js` and then `small.js`: ```html ``` -Browsers scan the page for scripts and download them in parallel, to improve performance. So in the example above both scripts download in parallel. The `small.js` probably finishes first. +Os navegadores examinam a página em busca de scripts e os baixam em paralelo para melhorar o desempenho. Portanto, no exemplo acima, os dois scripts sã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 a JavaScript library and then a script that depends on it. +Isso pode ser importante para os casos em que precisamos carregar uma biblioteca JavaScript e, em seguida, um script que depende dela. -```smart header="The `defer` attribute is only for external scripts" -The `defer` attribute is ignored if the ` -

...content after scripts...

+

...conteúdo depois dos scripts...

``` -- The page content shows up immediately: `async` doesn't block it. -- `DOMContentLoaded` may happen both before and after `async`, no guarantees here. -- A smaller script `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 scripts run 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. +- Um script menor `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 scripts are 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 scripts shouldn'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 scripts não devem esperar por eles: ```html - + ``` -```smart header="The `async` attribute is only for external scripts" -Just like `defer`, the `async` attribute is ignored if the `