Load CSS/Javascript in frontend conditionally if block is used

Well, the styles and scripts you register in your php register_block_type call should only be loaded when the block is in use if i recall correctly.

If you want to load additional scripts or styles to be enqueued only if there is a block of type “my-awesome/block-type”, you can use the has_block function in your wp_enqueue_scripts function like this:

add_action('wp_enqueue_scripts','enqueue_if_block_is_present');

function enqueue_if_block_is_present(){
  if(is_singular()){
     //We only want the script if it's a singular page
     $id = get_the_ID();
     if(has_block('my-awesome/block-type',$id)){
        wp_enqueue_script('my-awesome-script',$path_of_script,$needed_scripts,$version_of_script,$load_in_footer);
     }
  }
}

If you also want the script to be loaded on multiple views as well (like category archive or the blog page), you can hook into the the_content filter and enqueue the script there:

add_filter('the_content','enqueue_my_awesome_script_if_there_is_block');

function enqueue_my_awesome_script_if_there_is_block($content = ""){
  if(has_block('my-awesome/block-type')){
        wp_enqueue_script('my-awesome-script',$path_of_script,$needed_scripts,$version_of_script,true);
   //Be aware that for this to work, the load_in_footer MUST be set to true, as 
   //the scripts for the header are already echoed out at this point
     }
   return $content;
}

Happy Coding!

Leave a Comment