wordpress-themingwordpress-gutenberggutenberg-blocks

Enqueue styles and scripts for WordPress Gutenberg block


what are the best or the recommended way to Enqueue styles and scripts for WordPress Gutenberg block ?

i see some developers recommend enqueue_block_assets hook and others recommend init hook with refering to styles and scripts handles in register_block_type php function

What should i use ?


Solution

  • It does depends on the use case as not all cases are the same but I believe and stand to be corrected, Wordpress now recommends using register_block_type to add scripts and css instead.

    This is because adding it via block registration allows Wordpress to add the css only when a block is used.

    Test it and see. Add block assets using enqueue_block_assets and it will load on every page even if the block is not loaded on the page.

    The styles and scripts added below will only be added when the block is added to a page.

    My answer is based on some of my own testing recently. CSS Added via blocks using the register block are injected when a block is added not at load time like with enqueue_block_assets

    Also see this article as a reference in terms of it now being recommended by Wordpress

    register_block_type('namespace/your-block', array(
        'style' => 'view-style-handle',
        'editor_style' => 'editor-style-handle',
        'editor_script' => 'block-script-handle'
    ));