'How to initialize a javascript slider only on certain web pages

I have a website with several pages. there is a Swiper slider on the homepage. all pages have a main.js file where the slider is initialized. how do I make sure that the other pages don't get an error in the console?
Error:
Uncaught ReferenceError: Swiper is not defined



Solution 1:[1]

Looking into the Swiper API, you can see that it uses a class called Swiper to initialize the slider.

Since you just want to validate if the Swiper class is present in your page, you can simple test it's type:

if (typeof Swiper != undefined) {
   const swiper = new Swiper('.swiper');
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dahan Schuster