Is this a sensible method for adding multiple Scripts and CSS files to your Custom Blocks?

You can add just one CSS (“Style”) or two JS files (“Script”, “View script”) per Block Action.

But you can use ‘Enqueue style’ and ‘Enqueue script’ Actions and therein use the ‘Dependencies’ field where you us the Asset-ID from your Block.

Doing this, the additional files are loaded only if the Block exists on a page.

Do you think this is a sensible approach?

Screenshots:

@adamslowe how do you solve this? Would love to hear your thoughts about the enqueue-approach described here.

I’ve run into a similar situation where I need to load alpineJS and an Alpine plugin, and I don’t have an answer that I’m happy with. Rather than solve the problem, I’ve just been enqueuing them with a regular Enqueue Script Pinegrow action. The downside is that this will enqueue it site-wide rather than just on the pages where it’s needed.

I like where you are headed with your idea though. I’ll have to give it a try!

1 Like

Yeah, had some time to test this idea again. Unfortunately the asset-id changes if I do not use ACF block to an Unique-ID (like 1dc91d36a781778fe61872ec36ef71c2). Installing the same custom blocks plugin in another site the ID changes. So this idea may not be practical. :frowning:

@matjaz would it be possible to allow us to specify a callback for ‘enqueue_assets’ like ACF does? See ACF | acf_register_block_type()

I hardly wish we could enqueue additional assets only if a block is present on a page. :pleading_face:

for now this is working:

function my_additional_block_styles() {
    if(has_block('multiassets/my-img-splide')) {
        wp_enqueue_style( 'my-img-splide',  multiassets_plugin_base_url() . '/css/block_splide.css' );
        wp_enqueue_script( 'my-img-splide',  multiassets_plugin_base_url() . '/js/slider-init.js' );
    }
}
add_action( 'enqueue_block_assets', 'my_additional_block_styles' );