Last active
December 23, 2025 20:35
-
-
Save amrikmalhans/35841368a87aca5783cff92abfcde149 to your computer and use it in GitHub Desktop.
Initializing Swiper carousels on demand
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| FIRST = 10 | |
| swipers = [] // array aligned with cards, or WeakMap | |
| io = new IntersectionObserver((entries) => { | |
| for (entry of entries) { | |
| if (!entry.isIntersecting) continue | |
| card = entry.target | |
| io.unobserve(card) | |
| swiper = swipers.get(card) | |
| if (!swiper.initialized) swiper.init() | |
| } | |
| }, { threshold: 0, rootMargin: "0px 0px 50% 0px" }) | |
| for each cardEl with index i: | |
| container = cardEl.querySelector(".swiper") | |
| swiper = new Swiper(container, { | |
| init: i < FIRST, // true for first 10, false for rest | |
| loop: false, | |
| slidesPerView: 1, | |
| }) | |
| swipers.set(cardEl, swiper) | |
| if (i >= FIRST): | |
| io.observe(cardEl) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment