Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

216
Views
How to check if SwiperJS is available for use on a page?

I am using a single custom.js file in the footer for all of my websites pages.

In this custom.js there is the code that initializes the SwiperJS slider which is on the home page.

var swiper = new Swiper(".slider-1", {
    loop: true,
});

Now, I load the SwiperJS library on only the home page since it is only required there. But this results in the following error in the rest of the pages which don't have the script attached.

Uncaught ReferenceError: Swiper is not defined

The same also happens with the GLightbox library since I load it only on the gallery page but its initialization code is in the custom.js file.

How do I check if the library exists before running the initialization code?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

if (typeof Swiper !== 'undefined') {
  /* DO STUFF */
}
about 4 years ago · Juan Pablo Isaza Report

0

You can use try-catch

try {
  let swiper = new Swiper(".slider-1", {
    loop: true,
  });
}
catch (e) { /* console.log("no swiper") */ }

OR

const slider = document.querySelector(".slider-1");
if (slider) {
  let swiper = new Swiper(".slider-1", {
    loop: true,
  });
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!