How to only enqueue block javascript on the frontend when its needed [duplicate]

To register scripts/styles conditionally if the page has a certain block you can follow the solution that @Will posted in the comments from a similar question. Copy/pasting with some modifications from that question:

add_action( 'enqueue_block_assets', 'myplugin_enqueue_if_block_is_present' ); // Can only be loaded in the footer
// add_action( 'wp_enqueue_scripts', 'myplugin_enqueue_if_block_is_present' ); // Can be loaded in the both in head and footer
function myplugin_enqueue_if_block_is_present(){

    if ( has_block( 'my-plugin/my-block' ) ) {
        wp_enqueue_script(
            'myplugin_script',
            PATH_TO_ASSETS_FOLDER . 'frontend-script.js',
            array(),
            '1.0.0',
            true
        );
    }
}

If you need information from the block in order to enqueue a certain style or script one way to do this is to enqueue the scripts/styles in the render function of the block.

Beware that although this works we are mixing the enqueue function with the render callback. Another downside of this is that when the callback runs we are already in the content of the post. This means that we can only enqueue in the footer and not in the head.

add_action( 'init', 'myplugin_register_block' );
function myplugin_register_block() {

    register_block_type(
        'my-plugin/my-block',
        array(
            'editor_script'   => PATH_TO_ASSETS_FOLDER . 'editor-script.js',
            'render_callback' => 'myplugin_render_callback'
        )
    );
}

function myplugin_render_callback( $attributes, $content ) {

    // Do not enqueue if we are in the editor.
    // This will depend on your use case.
    if ( is_admin() ) {
        return $content;
    }

    wp_enqueue_style(
        'myplugin_style',
        PATH_TO_ASSETS_FOLDER . $attributes['some_attribute'] . '-style.css',
        array(),
        '1.0.0'
    );

    return $content;
}

Leave a Comment