landing / image-loading.js
yonghyunk1m's picture
Recover transient image failures and serve lossless illustration crops
7ff71f0 verified
Raw History Blame Contribute Delete
917 Bytes
'use strict';
// A transient image request failure must not require reloading the whole page.
// Keep retries finite, including failures that happened before this deferred script ran.
document.querySelectorAll('img[src^="assets/"]').forEach(img => {
const original = new URL(img.getAttribute('src'), document.baseURI);
let attempts = 0;
let pending = false;
function recover() {
if (pending || attempts >= 2 || !img.complete || img.naturalWidth > 0) return;
pending = true;
const attempt = ++attempts;
setTimeout(() => {
pending = false;
if (!img.isConnected || !img.complete || img.naturalWidth > 0) return;
const retry = new URL(original.href);
retry.searchParams.set('tj_image_retry', String(attempt));
img.src = retry.href;
}, attempt * 750);
}
img.addEventListener('error', recover);
window.addEventListener('pageshow', recover);
recover();
});