Last active
September 14, 2024 00:09
-
-
Save khoipro/f850c3f4c92a259b21a8fa47d1ed0bcc to your computer and use it in GitHub Desktop.
Load swiper slides lazyload (with <noscript> tag) for each slide
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
import { select, selectAll, hasClass, removeClass, loadNoscriptContent } from 'lib/dom' | |
import Swiper, { Navigation } from 'swiper' | |
export default el => { | |
const sliderEl = select('.js-slider', el) | |
const slideEls = selectAll('.swiper-slide', el) | |
if (sliderEl) { | |
const swiper = new Swiper(sliderEl, { | |
freeMode: true, | |
loop: true, | |
modules: [Navigation], | |
navigation: { | |
nextEl: '.swiper-button-next', | |
prevEl: '.swiper-button-prev' | |
}, | |
slidesPerView: 'auto', | |
spaceBetween: 10, | |
speed: 600, | |
autoplay: { | |
delay: 5000 | |
} | |
}) | |
swiper.navigation.init() | |
swiper.on('activeIndexChange', (swiper) => { | |
const activeIndex = swiper.realIndex | |
const activeSlideEl = slideEls[activeIndex] | |
if (hasClass('is-not-loaded', activeSlideEl)) { | |
loadNoscriptContent(activeSlideEl) | |
} | |
}) | |
} | |
} |
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
<div class="swiper js-slider"> | |
<div class="mhs-hero-slider__content swiper-wrapper"> | |
<?php foreach($images as $index => $slide) : | |
$item_class = 'swiper-slide mhs-hero-slider__item'; | |
$is_lazy_load = false; | |
if ($index > 0) { | |
$item_class .= ' is-not-loaded'; | |
$is_lazy_load = true; | |
} | |
?> | |
<div class="<?php echo esc_attr( $item_class ); ?>"> | |
<?php if ($is_lazy_load) : ?><noscript><?php endif; ?> | |
<picture class="image image--default mhs-hero-slider__image"> | |
<?php echo wp_get_attachment_image( | |
$slide['image'], | |
'large', | |
false, | |
array( | |
'class' => 'wp-post-image image__img' | |
) | |
); ?> | |
</picture> | |
<?php if ($is_lazy_load) : ?></noscript><?php endif; ?> | |
</div> | |
<?php endforeach; ?> | |
</div> | |
<div class="swiper-button-prev"></div> | |
<div class="swiper-button-next"></div> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment