Skip to content

Resource loading: onload and onerror #304

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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
10 changes: 5 additions & 5 deletions 2-ui/5-loading/03-onload-onerror/1-load-img-callback/solution.md
Original file line number Diff line number Diff line change
@@ -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()`.
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,21 @@
}
}

// ---------- The test ----------
// ---------- Тест ----------

let sources = [
"https://en.js.cx/images-load/1.jpg",
"https://en.js.cx/images-load/2.jpg",
"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++) {
Expand All @@ -46,7 +46,7 @@
alert(widthSum);
}

// should output 300
// має вивести 300
preloadImages(sources, testLoaded);
</script>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,24 @@

<script>
function preloadImages(sources, callback) {
/* your code */
/* ваш код */
}

// ---------- The test ----------
// ---------- Тест ----------

let sources = [
"https://en.js.cx/images-load/1.jpg",
"https://en.js.cx/images-load/2.jpg",
"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 immediately
// для кожного зображення,
// створімо інший img з тим же src і перевіримо, чи маємо його ширину відразу
function testLoaded() {
let widthSum = 0;
for (let i = 0; i < sources.length; i++) {
Expand All @@ -35,7 +35,7 @@
alert(widthSum);
}

// every image is 100x100, the total width should be 300
// кожне зображення має розмір 100x100, загальна ширина повинна бути 300
preloadImages(sources, testLoaded);
</script>

Expand Down
22 changes: 11 additions & 11 deletions 2-ui/5-loading/03-onload-onerror/1-load-img-callback/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,35 @@ importance: 4

---

# Load images with a callback
# Завантажте зображення з колбеком

Normally, images are loaded when they are created. So when we add `<img>` to the page, the user does not see the picture immediately. The browser needs to load it first.
Зазвичай зображення завантажуються під час їх створення. Тому, коли ми додаємо `<img>` на сторінку, користувач не відразу бачить зображення. Спочатку його потрібно завантажити браузеру.

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`.
Loading