FIX: Ensure loading thumbnails are used in Safari (#18204)

In Safari, `img.complete` is sometimes true even before the image is loaded. Checking for the presence of `img.naturalHeight` seems to be more reliable. It is very difficult to write a test for this behaviour due to the dependence on network conditions, scroll location, etc.

`img.naturalHeight` is supported by all our target browsers, and I have verified the functionality of this commit in Chrome, Safari and Firefox.
This commit is contained in:
David Taylor 2022-09-10 13:51:57 +02:00 committed by GitHub
parent 415535d577
commit 56832adf17
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 7 additions and 1 deletions

View File

@ -9,13 +9,19 @@ function forEachImage(post, callback) {
});
}
function isLoaded(img) {
// In Safari, img.complete sometimes returns true even when the image is not loaded.
// naturalHeight seems to be a more reliable check
return !!img.naturalHeight;
}
export function nativeLazyLoading(api) {
api.decorateCookedElement(
(post) =>
forEachImage(post, (img) => {
img.loading = "lazy";
if (img.dataset.smallUpload) {
if (!img.complete) {
if (!isLoaded(img)) {
if (!img.onload) {
img.onload = () => {
img.style.removeProperty("background-image");