Skip to content

Commit

Permalink
Previews lazy loading
Browse files Browse the repository at this point in the history
  • Loading branch information
vslinko committed May 14, 2024
1 parent 0f9ba57 commit d8e7f6b
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 2 deletions.
36 changes: 36 additions & 0 deletions bookmarks/frontend/behaviors/image-lazy-loading.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Behavior, registerBehavior } from "./index";

class ImageLazyLoading extends Behavior {
constructor(element) {
super(element);

const src = element.getAttribute("ld-img-lazy-load");
if (!src) {
return;
}

if (!window.IntersectionObserver) {
element.loading = "lazy";
element.src = src;
return;
}

// Prefer IntersectionObserver over loading=lazy
// because Safari still loads images when loading=lazy
let observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting) {
element.src = src;
observer.disconnect();
observer = null;
}
},
{
rootMargin: "0px 0px 100% 0px",
}
);
observer.observe(element);
}
}

registerBehavior("ld-img-lazy-load", ImageLazyLoading);
1 change: 1 addition & 0 deletions bookmarks/frontend/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import "./behaviors/fetch";
import "./behaviors/form";
import "./behaviors/modal";
import "./behaviors/global-shortcuts";
import "./behaviors/image-lazy-loading";
import "./behaviors/tag-autocomplete";
export { default as TagAutoComplete } from "./components/TagAutocomplete.svelte";
export { default as SearchAutoComplete } from "./components/SearchAutoComplete.svelte";
Expand Down
2 changes: 1 addition & 1 deletion bookmarks/templates/bookmarks/bookmark_list.html
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@
</div>
</div>
{% if bookmark_list.show_preview_images and bookmark_item.preview_image_file %}
<img class="preview-image" src="{% static bookmark_item.preview_image_file %}"/>
<img class="preview-image" ld-img-lazy-load="{% static bookmark_item.preview_image_file %}"/>
{% endif %}
</li>
{% endfor %}
Expand Down
2 changes: 1 addition & 1 deletion bookmarks/tests/test_bookmarks_list_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ def assertPreviewImage(self, html: str, bookmark: Bookmark, visible=True):

url = f"/static/{bookmark.preview_image_file}"
self.assertIsNotNone(preview_image)
self.assertEqual(preview_image["src"], url)
self.assertEqual(preview_image["ld-img-lazy-load"], url)

def assertBookmarkURLCount(
self, html: str, bookmark: Bookmark, link_target: str = "_blank", count=0
Expand Down

0 comments on commit d8e7f6b

Please sign in to comment.