How can I use Masonry plugin in main.js

I want to use Masonry effect. That is why I added “masonry” as depends to my main.js file.

wp_enqueue_script( 'sage_js', asset_path( 'scripts/main.js' ), array( 'jquery', 'masonry' ), null, true );

thanks to this WordPress included his own /wp-includes/js/masonry.min.js file, and it is perfect for me - I do not have to worry about file of this library (Masonry).

But when I want to turn on masonry effect in my main.js file by

$('.masonry').masonry();

I got ERROR:
TypeError: $(’.masonry’).masonry is not a function


How can I got access to masonry method?

1 Like

Have you tried installing the script conventionally using Bower?

bower install --save masonry

It should then autocompile Masonry into your dependencies. You won’t need to worry about using the WP version that might have features different to the original.

Failing that you can reference masonry in assets/manifest.json,but I would only do this as a last resort, as it will be picked up by jslint:


"dependencies": {
    "main.js": {
      "files": [
        "scripts/main.js",
        "path/to/masonry.js"
      ],
      "main": true
    },

I know that I can use Bower (I tested it and it works) and I know that my idea is not recommended but in my situation it will be the best option. I want to use the built-in WordPress version of Masonry, and I want to know how can I do this.

Why? Because if I use Bower - it compile Masonry library with main.js and finally main.js file will be too big.
Masonry effect will be using only on one page on my website and I want to enqueue it (masonry.pkgd.min.js) only on this page, and in main.js file I want to add condition:

if ( $('.masonry').length ) { /* turn on masonry effect */ }

Yeah, there’s a masonry packaged w/ WordPress. Assuming you’ve confirmed Masonry is enqueued on the page? Do you have a link where we can see this in action?

Yes, Masonry (built-in WordPress) is turned on, and WP included masonry.min.js file.
Sorry, for now the project is only on my localhost.
I will publish it soon…

Have you tried not adding masonry as a dependency of main.js?

For example:

wp_enqueue_script('masonry', 'jquery');

That should get you up and running (it works for me).

If you think it through, masonry is not a dependency of main.js - it’s the other way around.

Masonry is a dependency of jquery. If main.js is calling masonry, then those portions of main.js are dependencies of masonry.

Does this help, or did I completely misunderstand?