diff --git a/2-ui/5-loading/03-onload-onerror/1-load-img-callback/solution.md b/2-ui/5-loading/03-onload-onerror/1-load-img-callback/solution.md index 4b8fe50b4..12ea34d2c 100644 --- a/2-ui/5-loading/03-onload-onerror/1-load-img-callback/solution.md +++ b/2-ui/5-loading/03-onload-onerror/1-load-img-callback/solution.md @@ -1,6 +1,6 @@ -The algorithm: -1. Make `img` for every source. -2. Add `onload/onerror` for every image. -3. Increase the counter when either `onload` or `onerror` triggers. -4. When the counter value equals to the sources count -- we're done: `callback()`. +Алгоритм: +1. Зробіть `img` для кожного джерела. +2. Додайте `onload/onerror` для кожного зображення. +3. Збільште лічильник, коли спрацьовує `onload` або `onerror`. +4. Коли значення лічильника дорівнює кількості джерел, ми закінчили: `callback()`. diff --git a/2-ui/5-loading/03-onload-onerror/1-load-img-callback/solution.view/index.html b/2-ui/5-loading/03-onload-onerror/1-load-img-callback/solution.view/index.html index 50b9e741d..6ce131d16 100644 --- a/2-ui/5-loading/03-onload-onerror/1-load-img-callback/solution.view/index.html +++ b/2-ui/5-loading/03-onload-onerror/1-load-img-callback/solution.view/index.html @@ -21,7 +21,7 @@ } } - // ---------- The test ---------- + // ---------- Тест ---------- let sources = [ "https://en.js.cx/images-load/1.jpg", @@ -29,13 +29,13 @@ "https://en.js.cx/images-load/3.jpg" ]; - // add random characters to prevent browser caching + // додайте випадкові символи, щоб запобігти кешуванню браузера for (let i = 0; i < sources.length; i++) { sources[i] += '?' + Math.random(); } - // for each image, - // let's create another img with the same src and check that we have its width + // для кожного зображення, + // створімо інший img з тим же src і перевіримо, чи маємо його ширину відразу function testLoaded() { let widthSum = 0; for (let i = 0; i < sources.length; i++) { @@ -46,7 +46,7 @@ alert(widthSum); } - // should output 300 + // має вивести 300 preloadImages(sources, testLoaded); diff --git a/2-ui/5-loading/03-onload-onerror/1-load-img-callback/source.view/index.html b/2-ui/5-loading/03-onload-onerror/1-load-img-callback/source.view/index.html index 799350232..8c91d0811 100644 --- a/2-ui/5-loading/03-onload-onerror/1-load-img-callback/source.view/index.html +++ b/2-ui/5-loading/03-onload-onerror/1-load-img-callback/source.view/index.html @@ -7,10 +7,10 @@ diff --git a/2-ui/5-loading/03-onload-onerror/1-load-img-callback/task.md b/2-ui/5-loading/03-onload-onerror/1-load-img-callback/task.md index b7583550b..a0878f655 100644 --- a/2-ui/5-loading/03-onload-onerror/1-load-img-callback/task.md +++ b/2-ui/5-loading/03-onload-onerror/1-load-img-callback/task.md @@ -2,35 +2,35 @@ importance: 4 --- -# Load images with a callback +# Завантажте зображення з колбеком -Normally, images are loaded when they are created. So when we add `` to the page, the user does not see the picture immediately. The browser needs to load it first. +Зазвичай зображення завантажуються під час їх створення. Тому, коли ми додаємо `` на сторінку, користувач не відразу бачить зображення. Спочатку його потрібно завантажити браузеру. -To show an image immediately, we can create it "in advance", like this: +Щоб відразу показати зображення, ми можемо створити його "заздалегідь", наприклад: ```js let img = document.createElement('img'); img.src = 'my.jpg'; ``` -The browser starts loading the image and remembers it in the cache. Later, when the same image appears in the document (no matter how), it shows up immediately. +Браузер починає завантажувати зображення і запам’ятовує його в кеші. Пізніше, коли те саме зображення з’являється в документі (незалежно від того, як), воно з’являється негайно. -**Create a function `preloadImages(sources, callback)` that loads all images from the array `sources` and, when ready, runs `callback`.** +**Створіть функцію `preloadImages(sources, callback)`, яка завантажує всі зображення з масиву `sources` і, коли буде готова, запускає `callback`.** -For instance, this will show an `alert` after the images are loaded: +Наприклад, після завантаження зображень буде відображатися `alert`: ```js function loaded() { - alert("Images loaded") + alert("Зображення завантажені") } preloadImages(["1.jpg", "2.jpg", "3.jpg"], loaded); ``` -In case of an error, the function should still assume the picture "loaded". +У разі помилки функція все одно повинна вважати картинку "завантаженою". -In other words, the `callback` is executed when all images are either loaded or errored out. +Іншими словами, `callback` виконується, коли всі зображення завантажуються або є помилка. -The function is useful, for instance, when we plan to show a gallery with many scrollable images, and want to be sure that all images are loaded. +Ця функція корисна, наприклад, коли ми плануємо показати галерею з великою кількістю зображень, які можна прокручувати, і хочемо бути впевненими, що всі зображення завантажені. -In the source document you can find links to test images, and also the code to check whether they are loaded or not. It should output `300`. +У вихідному документі ви можете знайти посилання на тестові зображення, а також код, щоб перевірити, завантажені вони чи ні. Він має вивести `300`. diff --git a/2-ui/5-loading/03-onload-onerror/article.md b/2-ui/5-loading/03-onload-onerror/article.md index 590e54ab4..4eabe1a2e 100644 --- a/2-ui/5-loading/03-onload-onerror/article.md +++ b/2-ui/5-loading/03-onload-onerror/article.md @@ -1,17 +1,17 @@ -# Resource loading: onload and onerror +# Завантаження ресурсів: onload та onerror -The browser allows us to track the loading of external resources -- scripts, iframes, pictures and so on. +Браузер дозволяє нам відстежувати завантаження зовнішніх ресурсів -- скриптів, фреймів, зображень тощо. -There are two events for it: +Для цього передбачено дві події: -- `onload` -- successful load, -- `onerror` -- an error occurred. +- `onload` -- успішне завантаження, +- `onerror` -- виявлено помилку. -## Loading a script +## Завантаження скрипта -Let's say we need to load a third-party script and call a function that resides there. +Скажімо, нам потрібно завантажити сторонній скрипт і викликати функцію, яка там знаходиться. -We can load it dynamically, like this: +Ми можемо завантажити його динамічно, наприклад: ```js let script = document.createElement('script'); @@ -20,106 +20,106 @@ 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. +...Але як запустити функцію, оголошену всередині цього скрипта? Нам потрібно почекати, поки скрипт завантажиться, і тільки тоді ми зможемо її викликати. ```smart -For our own scripts we could use [JavaScript modules](info:modules) here, but they are not widely adopted by third-party libraries. +Для наших власних скриптів ми могли б використовувати [модулі JavaScript](info:modules), але вони не набули широкого поширення у сторонніх бібліотеках. ``` ### script.onload -The main helper is the `load` event. It triggers after the script was loaded and executed. +Основним помічником є подія `load`. Вона запускається після завантаження та виконання скрипта. -For instance: +Наприклад: ```js run untrusted let script = document.createElement('script'); -// can load any script, from any domain +// можемо завантажувати будь-який скрипт з будь-якого домену 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 variable "_" - alert( _.VERSION ); // shows library version + // скрипт створює змінну "_" + alert( _.VERSION ); // показує версію бібліотеки }; */!* ``` -So in `onload` we can use script variables, run functions etc. +Тож у `onload` ми можемо використовувати змінні скрипта, виконувати функції тощо. -...And what if the loading failed? For instance, there's no such script (error 404) or the server is down (unavailable). +...А якщо не вдалося завантажити? Наприклад, такого сценарію немає (помилка 404) або сервер не працює (недоступний). ### script.onerror -Errors that occur during the loading of the script can be tracked in an `error` event. +Помилки, які виникають під час завантаження скрипта, можна відстежити за допомогою події `error`. -For instance, let's request a script that doesn't exist: +Наприклад, давайте запросимо скрипт, якого не існує: ```js run let script = document.createElement('script'); -script.src = "https://example.com/404.js"; // no such script +script.src = "https://example.com/404.js"; // немає такого скрипта document.head.append(script); *!* script.onerror = function() { - alert("Error loading " + this.src); // Error loading https://example.com/404.js + alert("Помилка завантаження " + this.src); // Помилка завантаження 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. +Зверніть увагу, що ми не можемо отримати відомості про помилку HTTP тут. Ми не знаємо, чи була це помилка 404 чи 500 чи щось інше. Просто не вдалося завантажити. ```warn -Events `onload`/`onerror` track only the loading itself. +Події `onload`/`onerror` відстежують лише саме завантаження. -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. +Помилки, які можуть виникнути під час обробки та виконання скрипта, виходять за рамки цих подій. Тобто: якщо скрипт завантажується успішно, то запускається `onload`, навіть якщо в ньому є помилки програмування. Щоб відстежувати помилки скрипта, можна використовувати глобальний обробник `window.onerror`. ``` -## Other resources +## Інші ресурси -The `load` and `error` events also work for other resources, basically for any resource that has an external `src`. +Події `load` та `error` також працюють для інших ресурсів, в основному для будь-якого ресурсу, який має зовнішній `src`. -For example: +Наприклад: ```js run let img = document.createElement('img'); img.src = "https://js.cx/clipart/train.gif"; // (*) img.onload = function() { - alert(`Image loaded, size ${img.width}x${img.height}`); + alert(`Зображення завантажено, розмір ${img.width}x${img.height}`); }; img.onerror = function() { - alert("Error occurred while loading image"); + alert("Під час завантаження зображення сталася помилка"); }; ``` -There are some notes though: +Хоча є деякі примітки: -- Most resources start loading when they are added to the document. But `` is an exception. It starts loading when it gets a src `(*)`. -- For `