简体   繁体   中英

How can I run a jQuery function only when it's needed?

I've run into a problem where I have a responsive slider running on my site which has been added to an external .js file. I am running into an issue with a modal not popping up on the homepage because the page is looking for the slider which is only included on a couple of sub pages.

Chrome console is showing the following error: Uncaught TypeError: undefined is not a function

Here is my current code:

$('.my-carousel').slick({
    speed: 330,
    slidesToShow: 4,
});

You can check if plugin has been loaded like this (it checks if given jQuery function exists):

if ($().slick) {
 // .. your code
}

or

if ($.fn.slick) {
 // .. your code
}

You can just check if the carousel exists before calling the function like so:

var myCarousel = $('.my-carousel');
if (typeof myCarousel.slick !== 'undefined') {
  myCarousel.slick({speed: 330, slidesToShow: 4});
}

您可以使用length来检查它是否存在,例如:

if ($('.my-element').length) { //do stuff }

You can apply slick only if it is not applied, doing something like below:

$('.my-carousel').not('.slick-initialized').slick({
  // Your settings here.
});
if($('.my-carousel').length){
   $('.my-carousel').slick({
      speed: 330,
      slidesToShow: 4,
   });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM