Skip to content

Conversation

@principis
Copy link

@principis principis commented Jun 26, 2025

Load thumbnails only when visible using the Intersection Observer API.

Solves #965

Summary by CodeRabbit

  • New Features

    • Introduced an option to enable lazy loading for gallery thumbnails, improving performance by loading images only as they come into view.
  • Bug Fixes

    • Removed an unnecessary debugging message from the console output.

Load thumbnails only when visible using the Intersection
Observer API
@coderabbitai
Copy link

coderabbitai bot commented Jun 26, 2025

Walkthrough

A debugging console.log statement was removed from the utility file. The thumbnail plugin was updated to support lazy loading of thumbnail images via a new thumbnailLazyLoad setting, which adds IntersectionObserver-based logic for loading thumbnails only when they enter the viewport. The relevant interface, default settings, and class methods were updated accordingly.

Changes

File(s) Change Summary
src/lg-utils.ts Removed a debugging console.log statement from the getDynamicOptions method.
src/plugins/thumbnail/lg-thumbnail-settings.ts Added thumbnailLazyLoad boolean property to ThumbnailsSettings interface and default config.
src/plugins/thumbnail/lg-thumbnail.ts Implemented lazy loading for thumbnails using IntersectionObserver, updating relevant methods.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Thumbnail
    participant IntersectionObserver

    User->>Thumbnail: Initialize with settings (thumbnailLazyLoad)
    Thumbnail->>IntersectionObserver: Create observer (if lazy loading enabled)
    loop For each thumbnail
        Thumbnail->>Thumbnail: getThumbHtml()
        alt thumbnailLazyLoad enabled
            Thumbnail->>Thumbnail: Set img src to placeholder, data-src to real URL
            Thumbnail->>IntersectionObserver: Observe img element
        else
            Thumbnail->>Thumbnail: Set img src to real URL
        end
    end
    IntersectionObserver->>Thumbnail: On img in viewport
    Thumbnail->>Thumbnail: Replace src with data-src, remove lazy class, unobserve
Loading

Poem

A hop and a skip, a lazy load trip,
Thumbnails now wait ‘til they’re seen,
No more logs to clutter the code,
Just images loading, crisp and clean.
The gallery’s lighter, the rabbit’s delight—
Thumbnails appear when the moment is right!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (1)
src/plugins/thumbnail/lg-thumbnail.ts (1)

531-539: Add observer cleanup to prevent memory leaks.

The destroy method should disconnect the IntersectionObserver to ensure proper cleanup and prevent potential memory leaks.

 destroy(): void {
     if (this.settings.thumbnail) {
+        this.observer.disconnect();
         this.$LG(window).off(`.lg.thumb.global${this.core.lgId}`);
         this.core.LGel.off('.lg.thumb');
         this.core.LGel.off('.thumb');
         this.$thumbOuter.remove();
         this.core.outer.removeClass('lg-has-thumb');
     }
 }
🧹 Nitpick comments (1)
src/plugins/thumbnail/lg-thumbnail.ts (1)

41-50: Core logic is solid, but consider enhancements.

The IntersectionObserver implementation correctly handles lazy loading. Consider these optional improvements:

  1. Add error handling for failed image loads
  2. Add configurable threshold/rootMargin options
  3. Use arrow function for consistency with modern JavaScript patterns

Optional enhanced implementation:

-        this.observer = new IntersectionObserver(function (entries, observer) {
-            entries.forEach(function (entry) {
-                if (entry.isIntersecting) {
-                    const lazyImage = <HTMLImageElement>entry.target;
-                    lazyImage.src = <string>lazyImage.dataset.src;
-                    lazyImage.classList.remove("lg-lazy-thumb");
-                    observer.unobserve(lazyImage);
-                }
-            });
-        });
+        this.observer = new IntersectionObserver((entries, observer) => {
+            entries.forEach((entry) => {
+                if (entry.isIntersecting) {
+                    const lazyImage = <HTMLImageElement>entry.target;
+                    const src = lazyImage.dataset.src;
+                    if (src) {
+                        lazyImage.src = src;
+                        lazyImage.classList.remove('lg-lazy-thumb');
+                        observer.unobserve(lazyImage);
+                    }
+                }
+            });
+        }, { rootMargin: '50px' });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 92717fc and bbf9bd5.

📒 Files selected for processing (3)
  • src/lg-utils.ts (0 hunks)
  • src/plugins/thumbnail/lg-thumbnail-settings.ts (2 hunks)
  • src/plugins/thumbnail/lg-thumbnail.ts (3 hunks)
💤 Files with no reviewable changes (1)
  • src/lg-utils.ts
🧰 Additional context used
🪛 ESLint
src/plugins/thumbnail/lg-thumbnail.ts

[error] 46-46: Replace "lg-lazy-thumb" with 'lg-lazy-thumb'

(prettier/prettier)


[error] 453-453: 'placeholder' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 453-453: Replace ·"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" with ⏎················'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC'

(prettier/prettier)


[error] 454-454: Replace "lg-lazy-thumb" with 'lg-lazy-thumb'

(prettier/prettier)

🔇 Additional comments (4)
src/plugins/thumbnail/lg-thumbnail-settings.ts (2)

88-91: LGTM! Well-designed API addition.

The new thumbnailLazyLoad setting is properly documented and follows the existing naming conventions in the interface.


115-115: Good default value choice.

Setting thumbnailLazyLoad to false by default ensures backward compatibility and opt-in behavior for the new lazy loading feature.

src/plugins/thumbnail/lg-thumbnail.ts (2)

35-35: LGTM! Clean property declaration.

The IntersectionObserver property is properly typed and positioned with other private properties.


470-475: LGTM! Proper observer integration.

The integration with the IntersectionObserver is well-implemented with proper null checking and conditional logic based on the setting.

Comment on lines +452 to +459
if (this.settings.thumbnailLazyLoad) {
let placeholder = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC";
img.className = "lg-lazy-thumb";
img.setAttribute('data-src', thumbImg);
img.src = placeholder;
} else {
img.src = thumbImg;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix formatting and const usage issues.

The lazy loading logic is correct, but address these static analysis issues:

-        if (this.settings.thumbnailLazyLoad) {
-            let placeholder = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC";
-            img.className = "lg-lazy-thumb";
+        if (this.settings.thumbnailLazyLoad) {
+            const placeholder =
+                'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC';
+            img.className = 'lg-lazy-thumb';
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (this.settings.thumbnailLazyLoad) {
let placeholder = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC";
img.className = "lg-lazy-thumb";
img.setAttribute('data-src', thumbImg);
img.src = placeholder;
} else {
img.src = thumbImg;
}
if (this.settings.thumbnailLazyLoad) {
const placeholder =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC';
img.className = 'lg-lazy-thumb';
img.setAttribute('data-src', thumbImg);
img.src = placeholder;
} else {
img.src = thumbImg;
}
🧰 Tools
🪛 ESLint

[error] 453-453: 'placeholder' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 453-453: Replace ·"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" with ⏎················'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC'

(prettier/prettier)


[error] 454-454: Replace "lg-lazy-thumb" with 'lg-lazy-thumb'

(prettier/prettier)

🤖 Prompt for AI Agents
In src/plugins/thumbnail/lg-thumbnail.ts around lines 452 to 459, replace the
mutable variable 'placeholder' with a 'const' since its value does not change,
and fix any inconsistent indentation or spacing to improve code formatting.
Ensure the assignment of className, attributes, and src properties follows
consistent style conventions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant