Home Forums Front-end Issues Style loading even if block not used. Reply To: Style loading even if block not used.

  • In case anyone can be helped with a resolution, this is how my register-blocks.php is now set up. The style and js is only being loaded on pages when the block is used.
    I was creating a slider using Tiny Slider, so this shows how to register & enqueue an outside CSS library and a custom CSS file.

    function custom_load_blocks(){
        // Enqueue the Tiny Slider CSS file from CDN
        wp_enqueue_style( 'tiny-slider-css', '' );
    // Register the stylesheet
        wp_register_style( 'tiny-css', get_stylesheet_directory_uri() . '/blocks/tiny-slider/tiny-slider.css' );
        // Register the blocks
        register_block_type( get_stylesheet_directory() . '/blocks/tiny-slider/block.json', array(
            'style' => 'tiny-css', 'tiny-slider-css', // Use the registered stylesheet handle
        ) );
        // Enqueue the Tiny Slider JS file from CDN
        wp_enqueue_script( 'tiny-slider-js', '', array(), '2.9.4', true );
        // Enqueue the Tiny Slider JavaScript file
        wp_enqueue_script( 'tiny-js', get_stylesheet_directory_uri() . '/blocks/tiny-slider/tiny-slider.js', array(), '1.0.0', true );
    add_action( 'init', 'custom_load_blocks' );