laraib laraib - 5 months ago 23
Javascript Question

How to avoid uncaught jQuery error

I am using Owl Carousel in my WordPress theme and currently applying jQuery inside my page while chances are that there may not be jQuery loaded until I am calling that function and it throws that error ... how to avoid that error ? I am using document . ready function as well ..... while I want to load jQuery in my footer only not in header as well ... any one to guide me please where am I wrong ?
here is the code i am using

$(document).ready(function() {
$('#portfolio-slider').owlCarousel({
loop: true,
margin: 10,
nav: true,
items: 3,
responsive: {
0: {
items: 2
},
600: {
items: 3
},
1000: {
items: 3
}
}
})
});




This is inside my page, while jquery is being loaded in footer ....

Answer

first of all, to avoid mistakes, wrap your code with:

(function($){
    // your code goes here
})(jQuery);

this will make sure that $ === jQuery

secodnly, when you enqueue your scripts in Wordpress, add jQuery as dependency:

wp_enqueue_script ( 'YourScript', 'your-script.js', array('jQuery') )

if you cannot do it as above, another approach is to use DOMContentLoaded handler, which is exactly what document.ready does, but without jQuery - when it fires, you should have jQuery available:

document.addEventListener('DOMContentLoaded', function() {
  $('#portfolio-slider').owlCarousel({
    loop: true,
    margin: 10,
    nav: true,
    items: 3,
    responsive: {
      0: {
        items: 2
      },
      600: {
        items: 3
      },
      1000: {
        items: 3
      }
    }
  })
});
Comments