Blocks – Enqueuing Styles and Scripts Conditionally
-
Hi,
I am a bit struggling with the WordPress documentation to understand the latest best practices to enqueuing assets for blocks. I would like to conditionally load assets only when a specific custom block is inserted into a page. Otherwise, the block assets should not be loaded.
As I am using the block.json approach (ver3) to register a block, and I assumed that scripts and styles of that block will be loaded only when the block is used. Well, they are loaded anyway (block is used or not).
When using the enqueue_block_assets action, the assets are added by wp to the Editor as well as the frontend, even if the block is not being used. Not sure what is the logic here. I found a filter called “render_block” that can be used as a workaround but I am not sure it is best practices. It will be great to get some feedback here.
Another more minor question is related to the passing the wp-ajax object so that the custom blocks will be able to call rest APIs (passing url and nonce). Is it possible to localize a script (wp_localize_script) that was defined using the block.json? where is the handler? I added a dummy empty script just for passing that object so blocks will be able to use it.
Thanks for the help,
Idan
- You must be logged in to reply to this topic.