I am registering a block with custom JS in the editor:
function my_block_assets() {
wp_register_script(
'my-block-js', //
plugins_url( '/dist/my-block.js', dirname( __FILE__ ) ),
array( 'jquery' ),
);
register_block_type(
'custom/my-block', array(
'style' => 'my-block-css',
'editor_style' => 'my-block-editor-css',
'editor_script' => 'my-block-js',
)
);
}
add_action( 'init', 'my_block_assets' );
I want to run my custom JS only if the custom block is added in the editor. I am doing like this:
$(window).on('load', function () {
var container = document.querySelector('.wp-block-custom-my-block');
if ( container ) {
// run custom js
}
});
This seems to work but may be slow. Is there any special JS function I can use to check if a block is added in the editor? I found ways to check for a block in PHP on the frontend using has_block()
but nothing for JS in the editor.
You can select many block specific data from the Block Data Module. That said, the following works in the backend:
if ( wp.data.select('core/blocks').getBlockType('custom/my-block') ) {
//run custom js
}
Concerning the Frontend, I am going with the has_block
function:
<?php
mycustomblock_frontend_scripts() {
if ( has_block( 'custom/my-block' ) ) {
wp_enqueue_script('my-block-frontend-script');
}
}
add_action( 'wp_enqueue_scripts', 'blockgallery_frontend_scripts' );