Load Masonry JS library only on blog page
-
I’m trying to get the WP core Masonry JS library to load only when I need it, not on the entire site, because on pages where Masonry is not used, imagesLoaded.js generates an error;
uncaught TypeError: Cannot read property ‘length’ of null
at f (imagesloaded.min.js?ver=3.2.0:1)
at new g (imagesloaded.min.js?ver=3.2.0:1)
at g (imagesloaded.min.js?ver=3.2.0:1)
at (index) :173This is what I have in my function.php, and it works just fine, except for the error I get on all none index.php:
/** * Add WP core Masonry Library. */ if ( ! function_exists('slug_scripts_masonry') ) : if ( ! is_admin() ) : function slug_scripts_masonry() { wp_enqueue_script('masonry'); wp_enqueue_style( 'masonry', get_template_directory_uri() . '/inc/masonry.css' ); } add_action( 'wp_enqueue_scripts', 'slug_scripts_masonry' ); endif; //! is_admin() endif; //! slug_scripts_masonry exists /* Initialize Masonry layout */ if ( ! function_exists( 'slug_masonry_init' )) : function slug_masonry_init() { ?> <script> //set the container that Masonry will be inside of in a var var container = document.querySelector('#masonry-loop'); //create empty var msnry var msnry; // initialize Masonry after all images have loaded imagesLoaded( container, function() { msnry = new Masonry( container, { itemSelector: '.masonry-entry' }); }); </script> <?php } add_action( 'wp_footer', 'slug_masonry_init', 777 ); endif; // ! slug_masonry_init exists
What I want is to load the Masonry script and layout only on my index.php, i.e. only when is_home.
I’ve tried this, but the Masonry layout is absent:
if ( is_home() ) { add_action( 'wp_enqueue_scripts', 'slug_scripts_masonry' ); }
Settings > Reading is set to a static front-page and blog page. I’m using WP 4.9.8.
Any thoughts? Thanks.
- The topic ‘Load Masonry JS library only on blog page’ is closed to new replies.