Conditionally Load Block Assets, Part 2
Another look at conditionally loading block assets for WordPress blocks, assets being JavaScript and CSS files loaded by the browser. In the previous post, I solved using heavy-handed testing of each post in the loop checking to see if it contains our block to load the assets.
The company I work for runs a few WordPress sites, and using this technique for every page on the site is a bit much, especially since the majority of the millions of posts will not be using the block I want to load assets for.
Learning from my Jetpack colleagues, they use the render_callback
function and server-side rendering to control assets. This function is called when a post containing that block is being rendered._ _It returns the content of the block typically passing the attributes to a PHP function to generate HTML.
However, I can use this with the $content
parameter and I don't even have to use PHP to generate; I can use the same content created by the save
function for the block.
So here's a better solution to conditionally loading assets.
register_block_type( 'mkaz/test-block', array(
'editor_script' => 'mkaz-test-block-script',
'render_callback' => function( $attribs, $content ) {
wp_enqueue_script( 'mkaz-test-block-client-asset' );
return $content;
}
) );
The render_callback
will get called for a post that contains the block, and will call the enqueue script function to loading the client side assets and return the content of the block. All the posts that do not contain the block, will have no extra code run.
You can see an example of this in action on the test/asset-loading branch in my test-block repo.