Swiper Slider: Hướng dẫn cài đặt, sự kiện và best practices

CD

Swiper là thư viện slider JavaScript mã nguồn mở phổ biến nhất hiện nay (41k GitHub stars). Nhẹ, hỗ trợ touch/mobile, hardware-accelerated transitions, và có đầy đủ API cho mọi nhu cầu slider.

Cài đặt Swiper

Dùng npm hoặc CDN:

# npm
npm install swiper

# CDN (cho HTML thuần)
# <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css" />
# <script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>

HTML structure cơ bản

<div class="swiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    <div class="swiper-slide">Slide 3</div>
  </div>
  <!-- Pagination -->
  <div class="swiper-pagination"></div>

  <!-- Navigation buttons -->
  <div class="swiper-button-prev"></div>
  <div class="swiper-button-next"></div>
</div>

Kích hoạt Swiper

import Swiper from 'swiper';
import 'swiper/css';

const swiper = new Swiper('.swiper', {
  loop: true,
  pagination: { el: '.swiper-pagination' },
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  },
});

Các tuỳ chọn phổ biến

const swiper = new Swiper('.swiper', {
  // Auto-play
  autoplay: { delay: 3000, disableOnInteraction: false },

  // Responsive breakpoints
  breakpoints: {
    640: { slidesPerView: 1, spaceBetween: 10 },
    768: { slidesPerView: 2, spaceBetween: 20 },
    1024: { slidesPerView: 3, spaceBetween: 30 },
  },

  // Effect
  effect: 'slide', // 'fade', 'cube', 'coverflow', 'flip', 'creative'
  speed: 600,

  // Navigation
  pagination: { el: '.swiper-pagination', clickable: true },

  // Scrollbar (thay cho pagination)
  scrollbar: { el: '.swiper-scrollbar', draggable: true },
});

Listen events

Swiper cung cấp nhiều sự kiện để bạn lắng nghe và xử lý:

const swiper = new Swiper('.swiper', {
  on: {
    init() { console.log('Swiper initialized', this.slides.length); },
    slideChange() { console.log('Slide changed to', this.realIndex); },
    reachEnd() { console.log('Reached last slide'); },
    autoplayStop() { console.log('Autoplay stopped'); },
  },
});

// Hoặc dùng .on() sau khi khởi tạo
swiper.on('slideChangeTransitionEnd', () => {
  console.log('Transition ended, active slide:', swiper.activeIndex);
});

swiper.on('progress', (progress) => {
  console.log('Swiper progress:', progress);
});

swiper.on('touchStart', (e) => {
  console.log('Touch start position:', e.x);
});

Thao tác programmatic

// Điều hướng
swiper.slideNext();           // Slide tiếp
swiper.slidePrev();           // Slide trước
swiper.slideTo(3);            // Đến slide index 3
swiper.slideTo(0, 500);       // Đến slide 0 trong 500ms

// Lấy thông tin
swiper.activeIndex;           // Index slide hiện tại
swiper.realIndex;             // Index thực (kể cả loop)
swiper.slides.length;         // Tổng số slides
swiper.isBeginning;           // Đang ở slide đầu?
swiper.isEnd;                 // Đang ở slide cuối?

// Điều khiển autoplay
swiper.autoplay.start();
swiper.autoplay.stop();

// Enable/Disable
swiper.enable();              // Bật tương tác
swiper.disable();             // Tắt tương tác

Thumbnail gallery (sync 2 swipers)

<!-- Main slider -->
<div class="swiper main-gallery">
  <div class="swiper-wrapper">
    <div class="swiper-slide"><img src="img1.jpg" alt=""></div>
    <div class="swiper-slide"><img src="img2.jpg" alt=""></div>
  </div>
</div>

<!-- Thumbnail slider -->
<div class="swiper thumbnail-gallery">
  <div class="swiper-wrapper">
    <div class="swiper-slide"><img src="img1.jpg" alt=""></div>
    <div class="swiper-slide"><img src="img2.jpg" alt=""></div>
  </div>
</div>
const galleryThumbs = new Swiper('.thumbnail-gallery', {
  spaceBetween: 10,
  slidesPerView: 4,
  freeMode: true,
  watchSlidesProgress: true,
});

const galleryMain = new Swiper('.main-gallery', {
  spaceBetween: 10,
  navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' },
  thumbs: { swiper: galleryThumbs },
});

Best Practices

  1. Lazy load images: Dùng preloadImages: false + lazy: true để load ảnh khi đến gần slide, giảm initial load time
  2. Disable on interaction: autoplay.disableOnInteraction: false — không dừng autoplay khi người dùng tương tác
  3. Destroy instance khi không dùng: Gọi swiper.destroy() trong React/Vue component cleanup để tránh memory leak
  4. Observer: observer: true, observeParents: true — Swiper tự động cập nhật khi DOM thay đổi (ẩn/hiện slider)
  5. A11y: Thêm a11y: true để Swiper tự thêm ARIA labels, keyboard navigation, focus management
  6. Virtual slides: Hàng nghìn slides? Dùng virtual: true — chỉ render slides cần thiết, không render hết cùng lúc

Swiper trong WordPress

Với WordPress theme custom, enqueue Swiper qua functions.php:

function my_theme_assets() {
  wp_enqueue_style('swiper-css', 'https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css');
  wp_enqueue_script('swiper-js', 'https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js', [], null, true);

  // Custom script
  wp_add_inline_script('swiper-js', '
    document.addEventListener("DOMContentLoaded", function() {
      new Swiper(".wp-block-my-slider", {
        loop: true,
        autoplay: { delay: 4000 },
        pagination: { el: ".swiper-pagination", clickable: true },
      });
    });
  ');
}
add_action('wp_enqueue_scripts', 'my_theme_assets');

Kết luận

Swiper là thư viện slider linh hoạt và đầy đủ tính năng nhất cho JavaScript. Từ gallery ảnh đơn giản đến carousel phức tạp với thumbnail, lazy load, virtual slides — Swiper đều hỗ trợ. Dùng Swiper 11+ cho bundle size nhỏ nhất và hiệu suất tốt nhất.

Tham khảo: swiperjs.com | GitHub

Bài cùng chủ đề: Sourcetree Git GUI | Lando local dev | Cloudflare Tunnel