How to enqueue scripts and styles only when there are needed?

I use the following to enqueue a specific script on post.php, which is triggered by the admin_enqueue_scripts hook:

if ( in_array( get_current_screen()->base, [ 'post' ] ) ) {
    // Load scripts only on the post edit page.
    wp_enqueue_script( PLUGIN_NAME, PLUGIN_ROOT_URL . 'resources/js/script.js', [], PLUGIN_VERSION, false );
}

Instead of the check I do, you could retrieve the post’s content and scan it for the block you require. Like so:

if ( is_singular() ) {
    $post = get_post();
    if ( $post && has_blocks( $post ) ) {
        $blocks = parse_blocks( $post->post_content );
        $postContainsBlock = ... // Search $blocks array for the required block.
            
        if ( $postContainsBlock ) {
            wp_enqueue_script( PLUGIN_NAME, PLUGIN_ROOT_URL . 'resources/js/script.js', [], PLUGIN_VERSION, false );
        }
    }
}

Note: I haven’t tested the code above.

Leave a Comment