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


Style loading even if block not used.

  • I’m creating an ACF block using block.json.

    In register-blocks.php, I’m registering the style as such:

    function custom_load_blocks(){
    	wp_register_style( 'tiny-css', get_stylesheet_directory_uri() . '/blocks/tiny-slider/tiny-slider.css' );
      	register_block_type( get_stylesheet_directory() . '/blocks/first-block/block.json' );
    	register_block_type( get_stylesheet_directory() . '/blocks/tiny-slider/block.json' );
    add_action( 'init', 'custom_load_blocks' );

    Then calling the style in block.json like ‘ “style”: “tiny-css”,’

    It’s working, however the tiny-slider.css is being loaded on every page on the site.
    How can I get the CSS to only be loaded when the block is used on the page?

  • 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' );
  • I’m having this issue with ACF Block styles being rendered even if they the block is not being used.

    In your solution, where does register-blocks.php live? Is it within /blocks/tiny-slider or top level in the theme folder?


Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.