9

I'm trying to make a Custom Gutenberg Block, but I'm having trouble with loading javascript that goes with this block.

On the front-end it works fine, but in the editor it seems that the script fires (even with DOMcontentloaded or window.onload) BEFORE the Gutenberg block itself is fully loaded.

Since my script targets an element in the block (which it can't find because the element hasn't loaded yet), it's not working correctly.

Any suggestions on how to make the script load AFTER the Custom Block has loaded fully in the editor?


(I'm using the ACF way of creating Custom blocks)

1 Answer 1

1

I couldn't find a built in ACF way of doing this.

Instead, in my block's PHP render function I added

printf( "<script>window.jQuery(window).trigger('acf/loaded/block-name');</script>" );

This uses jQuery as an event bus to trigger an event when the block is rendered. You might need to include a check that you're in the admin so the event won't be triggered in the frontend. My WordPress is headless so this wasn't an issue for me.

Then, in your JavaScript, you can do:

$( window ).on( 'acf/loaded/block-name', function() {
    // rest of your code here
} )

By including the block name in the event you can check different events for individual blocks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.