Maybe preload images (#2165)

This commit is contained in:
kelciour 2022-11-04 03:07:51 +03:00 committed by GitHub
parent fd2212a6cb
commit 3973f27ee4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 1 deletions

View File

@ -49,3 +49,17 @@ export function preloadAnswerImages(qHtml: string, aHtml: string): void {
diff.forEach((src) => injectPreloadLink(src, "image"));
}
}
export async function maybePreloadImages(html: string): Promise<void> {
const srcs = extractImageSrcs(html);
await Promise.race([
Promise.all(
srcs.map((src) => {
const img = new Image();
img.src = src;
return imageLoaded(img);
}),
),
new Promise((r) => setTimeout(r, 100)),
]);
}

View File

@ -16,7 +16,7 @@ globalThis.anki.mutateNextCardStates = mutateNextCardStates;
import { bridgeCommand } from "../lib/bridgecommand";
import { maybePreloadExternalCss } from "./css";
import { allImagesLoaded, preloadAnswerImages } from "./images";
import { allImagesLoaded, maybePreloadImages, preloadAnswerImages } from "./images";
declare const MathJax: any;
@ -133,6 +133,9 @@ export async function _updateQA(
// prevent flash of unstyled content when external css used
await maybePreloadExternalCss(html);
// prevent flickering & layout shift on image load
await maybePreloadImages(html);
qa.style.opacity = "0";
try {