Load CSS/Javascript in frontend conditionally if block is used

Assuming I have no infinite scroll or anything else going on in my theme:
Is there a way to enqueue my custom Gutenberg block styles and scripts so they are only (lazy) loaded in the front-end when the block is really used? Something like is_active_widget, just for blocks?

If I enqueue them inside a enqueue_block_assets function they’re added to any site.

On github, I found this https://github.com/WordPress/gutenberg/issues/5445 , but it sounds like it’s more on bundling than conditional load, so I still hope they didn’t leave that optimization opportunity out – otherwise any other site will soon be junked with 20 additional scripts from numerous Gutenberg block plugins people install and only use once on a page (think of large image gallery block scripts for example).

Thanks & Regards!

3

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