Skip to content

Instantly share code, notes, and snippets.

@sabrina-zeidan
Last active May 3, 2023 21:34
Show Gist options
  • Save sabrina-zeidan/0a06c02756df7efd6d3ceb90d041376b to your computer and use it in GitHub Desktop.
Save sabrina-zeidan/0a06c02756df7efd6d3ceb90d041376b to your computer and use it in GitHub Desktop.
Stop loading block's CSS and JS if the block is not used -- for Full Site Edit themes [WordPress]
// Avoid loading unused assets, both JS and CSS
// Removes both CSS and JS
// For Full Site Editing Theme!
// In a better world block's author makes sure the block's assests are loaded only if block is actually in use (via enqueue_block_assets). For other cases we can do it ourselves
// In this example I load Swiper's block assets only where the block is used
// TODO: Works for content on Singular content only. if block is elsewhere or it's archive use this https://wordpress.stackexchange.com/questions/392493/find-if-widget-block-is-active
add_filter( 'style_loader_tag', 'sz_stop_loading_unused_block_crap', 9999, 3 );
add_filter( 'script_loader_tag', 'sz_stop_loading_unused_block_crap', 10, 3 );
function sz_stop_loading_unused_block_crap( $tag, $handle, $src ) {
//The list of plugins/blocks to optimize: plugin directory & block name
$exclusions = [
['plugins/wp-swiper', 'da/wp-swiper-slide'],
['plugins/better-click-to-tweet', 'bctt/clicktotweet']
];
// to find out the name of the block in Browser Inspector (not source code) ctrl+f for "data-type"
if (!is_user_logged_in()){// for FE only
foreach ($exclusions as $exclusion){
// Check if block's assets are loaded
if (str_contains($src, $exclusion[0])) {
if ( is_singular() ){ // do on singular only
$id = get_the_ID();
if (has_block($exclusion[1], $id) !== true) {
$tag = '';
}
}
//elseif ( is_archive() ) { // I am not aware of checking which blocks are used on templates other than Singular - archives, search, homepage}
else { // not singular
$tag = ''; // do not load anywhere but singular all. Attention -- might be not what you need.
}
}
}
}
return $tag;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment