I wrote twice previously about solving this same problem. The first time, I solved checking if each post in the loop contains our block to load the assets. The better method to load conditionally was to use the
render_callback function to load the assets. You may still want to consider this method for more complex blocks that might have numerous assets.
In WordPress 5.8, there is now a built-in easy way to conditionally load assets. By specifying the style or script using the
register_block_type( 'mkaz/test-block', array( 'editor_script' => 'mkaz-test-block-script', 'editor_style' => 'mkaz-test-block-editor-style', 'style' => 'mkaz-test-block-style', 'script' => 'mkaz-test-block-frontend' ) );
If you then also specify the new opt-in filter:
add_filter( 'should_load_separate_core_block_assets', '__return_true' );
WordPress will only load the style or script files when the block is used, this works for both archive and single pages.
I have a branch on my test-block plugin that shows a full working plugin setup with this feature.
My test-block example is written in ES5 to simplify implementation and testing, this conditional asset loading also works using ESNext and the recommended block.json format to define your scripts and styles to load.
See the Block Styles dev note announcing this feature.