pFad - Phone/Frame/Anonymizer/Declutterfier! Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

URL: http://github.com/javascript-tutorial/uk.javascript.info/pull/304/files

" href="https://github.githubassets.com/assets/code-2d31826944fd3be8.css" /> Resource loading: onnload and onerror by OlhaBrozhenets · Pull Request #304 · javascript-tutorial/uk.javascript.info · GitHub
Skip to content
Merged
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

The algorithm:
1. Make `img` for every source.
2. Add `onnload/onerror` for every image.
3. Increase the counter when either `onnload` or `onerror` triggers.
4. When the counter value equals to the sources count -- we're done: `callback()`.
Алгоритм:
1. Зробіть `img` для кожного джерела.
2. Додайте `onnload/onerror` для кожного зображення.
3. Збільште лічильник, коли спрацьовує `onnload` або `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-onnload-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
pFad - Phonifier reborn

Pfad - The Proxy pFad © 2024 Your Company Name. All rights reserved.





Check this box to remove all script contents from the fetched content.



Check this box to remove all images from the fetched content.


Check this box to remove all CSS styles from the fetched content.


Check this box to keep images inefficiently compressed and original size.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy