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..b0485a555 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 +# Скрипти: async, defer -In modern websites, scripts are often "heavier" than HTML: their download size is larger, and processing time is also longer. +На сучасних вебсайтах скрипти часто "важчі" за HTML: їх розмір завантаження більший, і час обробки теж довший. -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. +Коли браузер завантажує HTML і зустрічає тег ``, він не може продовжувати будівництво DOM. Він повинен виконати скрипт прямо зараз. Те ж саме відбувається для зовнішніх скриптів ``: браузер повинен зачекати, щоб скрипт завантажився, виконати завантажений скрипт, і тільки тоді він може обробити решту сторінки. -That leads to two important issues: +Це призводить до двох важливих проблем: -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. Скрипти не можуть бачити елементи DOM під ними, тому вони не можуть додавати обробники тощо. +2. Якщо у верхній частині сторінки є громіздкий скрипт, він "блокує сторінку". Користувачі не можуть побачити вміст сторінки, поки він не завантажиться та не запуститься: ```html run height=100 -
...content before script...
+...вміст перед скриптом...
- -...content after 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: +Для цього є деякі обхідні шляхи. Наприклад, ми можемо розмістити скрипт внизу сторінки. Тоді він зможе бачити елементи над ним і не блокуватиме показ вмісту сторінки: ```html - ...all content is above the 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. +Але це рішення далеко не ідеальне. Наприклад, браузер помічає скрипт (і може почати його завантаження) лише після того, як повністю завантажить HTML-документ. Для великих документів HTML це може спричинити помітну затримку. -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. +Такі речі невидимі для людей, які використовують дуже швидкі з’єднання, але багато людей у світі все ще мають низьку швидкість Інтернету та використовують далеко не ідеальне мобільне інтернет-з’єднання. -Luckily, there are two ` - -...content after script...
+ +...вміст після скрипту...
``` -In other words: +Іншими словами: -- Scripts with `defer` never block the page. -- Scripts with `defer` always execute when the DOM is ready (but before `DOMContentLoaded` event). +- Скрипти з `defer` ніколи не блокують сторінку. +- Скрипти з `defer` завжди виконуються, коли DOM готово (але перед подією `DOMContentLoaded`). -The following example demonstrates the second part: +Наступний приклад демонструє другу частину: ```html run height=100 -...content before scripts...
+...вміст перед скриптами...
-...content after scripts...
+...вміст після скриптів...
``` -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. Вміст сторінки з’являється негайно. +2. Обробник події `DOMContentLoaded` чекає на відкладений скрипт. Він запускається лише тоді, коли скрипт буде завантажено та виконано. -**Deferred scripts keep their relative order, just like regular scripts.** +**Відкладені скрипти зберігають відносний порядок, як і звичайні скрипти.** -Let's say, we have two deferred scripts: the `long.js` and then `small.js`: +Скажімо, у нас є два відкладених скрипти: `long.js`, а потім `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. +Браузери сканують сторінку на наявність скриптів і завантажують їх паралельно, щоб підвищити продуктивність. Отже, у наведеному вище прикладі обидва скрипти завантажуються паралельно. `small.js`, ймовірно, завершується першим. -...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. +...Але атрибут `defer`, крім того, що каже браузеру "не блокувати", гарантує, що зберігається відносний порядок виконання. Тому навіть якщо `small.js` завантажується першим, він все ще чекає і запускається після виконання `long.js`. -That may be important for cases when we need to load a JavaScript library and then a script that depends on it. +Це може бути важливим в тих випадках, коли нам потрібно завантажити бібліотеку JavaScript, а потім скрипт, який залежить від неї. -```smart header="The `defer` attribute is only for external scripts" -The `defer` attribute is ignored if the ` -...content after 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. +- Вміст сторінки з’являється відразу: `async` не блокує його. +- `DOMContentLoaded` може відбуватися як до, так і після `async`, тут немає гарантій. +- Менший скрипт `small.js` йде другим, але, ймовірно, завантажується перед `long.js`, тому `small.js` запускається першим. Хоча, можливо, `long.js` завантажується спочатку, якщо він кешується, то він запускається першим. Іншими словами, асинхронні сценарії виконуються в порядку "першим завантажився -- першим виконався". -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: +Асинхронні сценарії чудові, коли ми додаємо до сторінки незалежний сторонній скрипт: лічильники, рекламу тощо, оскільки вони не залежать від наших скриптів, і наші скрипти не повинні їх чекати: ```html - + ``` -```smart header="The `async` attribute is only for external scripts" -Just like `defer`, the `async` attribute is ignored if the `