webpack-bootstrap-ui-kit/src/js/ajax/lazy-images.js

80 lines
2.5 KiB
JavaScript
Raw Normal View History

2021-08-09 18:04:09 +02:00
// browser tab visibility state detection
2021-08-18 20:51:15 +02:00
import Events from "../_events";
import Consts from "../_consts";
2021-08-09 18:04:09 +02:00
2021-08-18 20:51:15 +02:00
const axios = require("axios");
2021-08-09 18:04:09 +02:00
export default ((W) => {
2021-08-18 20:51:15 +02:00
const NAME = "main.lazy-images";
2021-08-09 18:04:09 +02:00
const D = document;
const BODY = D.body;
const API_STATIC = document.querySelector('meta[name="api_static_domain"]');
2021-08-18 20:51:15 +02:00
const API_STATIC_URL = API_STATIC
? API_STATIC.getAttribute("content")
: `${window.location.protocol}//${window.location.host}`;
2021-08-09 18:04:09 +02:00
console.log(`${NAME} [static url]: ${API_STATIC_URL}`);
const loadLazyImages = () => {
console.log(`${NAME}: Load lazy images`);
D.querySelectorAll(`[data-lazy-src]`).forEach((el) => {
2021-08-18 20:51:15 +02:00
el.classList.remove("empty");
el.classList.add("loading");
el.classList.remove("loading__network-error");
2021-08-09 18:04:09 +02:00
2021-08-18 20:51:15 +02:00
const attr = el.getAttribute("data-lazy-src");
const imageUrl = attr.startsWith("http") ? attr : API_STATIC_URL + attr;
2021-08-09 18:04:09 +02:00
// offline response will be served by caching service worker
axios
.get(imageUrl, {
2021-08-18 20:51:15 +02:00
responseType: "blob",
2021-08-09 18:04:09 +02:00
})
.then((response) => {
const reader = new FileReader(); // https://developer.mozilla.org/en-US/docs/Web/API/FileReader/FileReader
reader.readAsDataURL(response.data);
reader.onload = () => {
const imageDataUrl = reader.result;
2021-08-18 20:51:15 +02:00
el.setAttribute("src", imageDataUrl);
el.classList.remove("loading");
el.classList.add("loading__success");
2021-08-09 18:04:09 +02:00
};
})
.catch((e) => {
//el.setAttribute('src', imageUrl);
if (e.response) {
switch (e.response.status) {
case 404:
2021-08-18 20:51:15 +02:00
msg = "Not Found.";
2021-08-09 18:04:09 +02:00
break;
case 500:
2021-08-18 20:51:15 +02:00
msg = "Server issue, please try again latter.";
2021-08-09 18:04:09 +02:00
break;
default:
2021-08-18 20:51:15 +02:00
msg = "Something went wrong.";
2021-08-09 18:04:09 +02:00
break;
}
console.error(`${NAME} [${imageUrl}]: ${msg}`);
} else if (e.request) {
2021-08-18 20:51:15 +02:00
msg = "No response received";
2021-08-09 18:04:09 +02:00
console.error(`${NAME} [${imageUrl}]: ${msg}`);
} else {
console.error(`${NAME} [${imageUrl}]: ${e.message}`);
}
2021-08-18 20:51:15 +02:00
el.classList.remove("loading");
el.classList.add("loading__network-error");
el.classList.add("empty");
2021-08-09 18:04:09 +02:00
});
});
};
W.addEventListener(`${Events.LODEDANDREADY}`, loadLazyImages);
W.addEventListener(`${Events.AJAX}`, loadLazyImages);
})(window);