Enhance lazy loading for backgrounds

e39eec2c6fbd20273d63536b22a27ff67d55fa13

Cohee <18619528+Cohee1207@users.noreply.github.com>

1 files changed, +26 -14Ignore whitespace
public/scripts/backgrounds.js+26 -14
@@ -479,12 +479,14 @@ function activateLazyLoader() {
479479 lazyLoadObserver = new IntersectionObserver((entries, observer) => {
480480 entries.forEach(entry => {
481481 if (entry.target instanceof HTMLElement && entry.isIntersecting) {
482482 const imageUrltarget = entry.target.dataset.bgSrc;
483- if (imageUrl) {
483+ const bg = target.getAttribute('bgfile');
484- entry.target.style.backgroundImage = `url('${imageUrl}')`;
484+ const isCustom = target.getAttribute('custom') === 'true';
485- }
485+ resolveImageUrl(bg, isCustom)
486- entry.target.classList.remove('lazy-load-background');
486+ .then(url => { target.style.backgroundImage = url; })
487- observer.unobserve(entry.target);
487+ .catch(() => { target.style.backgroundImage = PLACEHOLDER_IMAGE; });
488+ target.classList.remove('lazy-load-background');
489+ observer.unobserve(target);
488490 }
489491 });
490492 }, options);
@@ -508,6 +510,24 @@ function generateUrlParameter(bg, isCustom) {
508510}
509511
510512/**
513+ * Resolves the image URL for the background.
514+ * @param {string} bg Background file name
515+ * @param {boolean} isCustom Is a custom background
516+ * @returns {Promise<string>} CSS URL of the background
517+ */
518+async function resolveImageUrl(bg, isCustom) {
519+ const fileExtension = bg.split('.').pop().toLowerCase();
520+ const isAnimated = ['mp4', 'webp'].includes(fileExtension);
521+ const thumbnailUrl = isAnimated && !background_settings.animation
522+ ? await getThumbnailFromStorage(bg)
523+ : isCustom
524+ ? bg
525+ : getThumbnailUrl('bg', bg);
526+
527+ return `url('${thumbnailUrl}')`;
528+}
529+
530+/**
511531 * Instantiates a background template
512532 * @param {string} bg Path to background
513533 * @param {boolean} isCustom Whether the background is custom
@@ -518,19 +538,11 @@ async function getBackgroundFromTemplate(bg, isCustom) {
518538 const url = generateUrlParameter(bg, isCustom);
519539 const title = isCustom ? bg.split('/').pop() : bg;
520540 const friendlyTitle = title.slice(0, title.lastIndexOf('.'));
521- const fileExtension = bg.split('.').pop().toLowerCase();
522- const isAnimated = ['mp4', 'webp'].includes(fileExtension);
523- const thumbnailUrl = isAnimated && !background_settings.animation
524- ? await getThumbnailFromStorage(bg)
525- : isCustom
526- ? bg
527- : getThumbnailUrl('bg', bg);
528541
529542 template.attr('title', title);
530543 template.attr('bgfile', bg);
531544 template.attr('custom', String(isCustom));
532545 template.data('url', url);
533- template.attr('data-bg-src', thumbnailUrl);
534546 template.addClass('lazy-load-background');
535547 template.css('background-image', PLACEHOLDER_IMAGE);
536548 template.find('.BGSampleTitle').text(friendlyTitle);