I’m aware about jQuery noConflict wrappers, and using wp_enqueue_script()
to load my scripts. Following underscore (_s) starter theme, I’m enqueueing my script (example.js
) with the dependency of jQuery in the footer. And to avoid ‘Render Blocking javacript’ warning I pasted all my separate jQuery code in that single file.
Suppose,
- I have a slider function there, specific to the
front-page.php
, - but TinyNav function there, specific to all the pages of the site,
- and Isotope function specific to only the Portfolio page
example.js
:
jQuery(document).ready(function($) {
//add .js to html
$('html').removeClass('no-js').addClass('js');
//front-page slider code
//$('container').doSlider();
//portfolio page isotope code
//$('container').activeIsotope();
});
All the code are working well with no conflict with each other. And they are getting jQuery as well. So the isotope part is working fine in portfolio page with no error, but is showing an error in other pages where the isotope container is not present. Even with the document.ready wrapper it’s showing that error.
//portfolio page isotope code
$(document).ready(function(){
var container = $('#portfolio-holder');
container.imagesLoaded( function(){
container.isotope({
itemSelector : '.portfolio-item',
layoutMode : 'fitRows',
animationEngine : 'jquery'
});
/* ---- Filtering ----- */
$('#portfolio-filter li').click(function(){
var $this = $(this);
if ( $this.hasClass('selected') ) {
return false;
} else {
$('#portfolio-filter .selected').removeClass('selected');
var filterValue = $(this).attr('data-filter');
container.isotope({ filter: filterValue });
$this.addClass('selected');
return false;
}
});
});
});
The error is:
Uncaught TypeError: undefined is not a function
and the error is pointing to:
container.imagesLoaded( function(){
The same problem happened in another project of mine where it’s showing error for flexslider. Then I separated the plugin code to another file and load that file only specific to that page where the slider is present.
But how can I load all my javascripts from a single file with noConflict and no error where the DOM is absent?
Simply check if the container and the function exists before calling it: