How to load an additional script for a block in the block editor?
I'm developing a dynamic block that prints the following markup (for example) using the ServerSideRender
component:
div class=accordion
h3 class=accordion-titleA title/h3
div class=accordion-contentLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat./div
/div
To fully work this block needs the Accordion
component from jQuery UI:
accordion-jquery-start.js
file:
( function( $ ) {
$( function() {
$( '.accordion' ).accordion( {
header: 'h3',
heightStyle: 'content',
animate: 100,
collapsible: true,
active: false
} );
} );
} )( jQuery );
I'm registering my dynamic block using:
register_block_type( 'my/accordion-block', array(
'style' = 'accordion-block-css',
'editor_script' = 'accordion-block-js',
'render_callback' = 'render_block',
);
To load the additional script shown above in the block editor, I'm using the enqueue_block_editor_assets
action:
function my_enqueue_block_editor_assets() {
wp_enqueue_script( 'accordion-jquery-start', plugins_url( '/assets/js/accordion-jquery-start.js', __FILE__ ), array( 'jquery', 'jquery-ui-accordion', 'accordion-block-js' ), false, true );
}
add_action( 'enqueue_block_editor_assets', 'my_enqueue_block_editor_assets' );
Almost everything works: the block is registered and prints the correct markup and all of the needed scripts and styles get enqueued. BUT, for some reason, the accordion
function from jQuery UI doesn't get attached to the .accordion
class of my block in the block editor, so the accordion effect doesn't work. But, there's no console errors anywhere. It seems that the accordion-jquery-start.js
script is run before the block itself is fully loaded.
Any ideas? Should I load the accordion-jquery-start.js
script differently?
Topic block-editor jquery-ui Wordpress javascript
Category Web