delay scrolling to answer until images load

This commit is contained in:
Damien Elmes 2021-03-22 12:05:18 +10:00
parent 87801668e9
commit c3145977f0

View file

@ -73,6 +73,9 @@ async function _updateQA(
}) })
.catch(renderError("MathJax")); .catch(renderError("MathJax"));
// defer display for up to 100ms to allow images to load
await Promise.race([allImagesLoaded(), new Promise((r) => setTimeout(r, 100))]);
// and reveal when processing is done // and reveal when processing is done
await qa.fadeTo(fadeTime, 1).promise(); await qa.fadeTo(fadeTime, 1).promise();
await _runHook(onShownHook); await _runHook(onShownHook);
@ -111,11 +114,9 @@ function _showAnswer(a: string, bodyclass: string): void {
document.body.className = bodyclass; document.body.className = bodyclass;
} }
// scroll to answer? // avoid scrolling to the answer until images load, even if it
var e = $("#answer"); // takes more than 100ms
if (e[0]) { allImagesLoaded().then(scrollToAnswer);
e[0].scrollIntoView();
}
}, },
function () {} function () {}
) )
@ -162,3 +163,23 @@ function _emulateMobile(enabled: boolean): void {
list.remove("mobile"); list.remove("mobile");
} }
} }
function allImagesLoaded(): Promise<void[]> {
return Promise.all(
Array.from(document.getElementsByTagName("img")).map(imageLoaded)
);
}
function imageLoaded(img: HTMLImageElement): Promise<void> {
if (img.complete) {
return;
}
return new Promise((resolve) => {
img.addEventListener("load", () => resolve());
img.addEventListener("error", () => resolve());
});
}
function scrollToAnswer(): void {
document.getElementById("answer")?.scrollIntoView();
}