Hidden blocks may still be doing all the work

While testing the WordPress Block Logic plugin, we discovered that blocks hidden by its conditions may still be rendered behind the scenes.

They disappear from the finished page, so everything looks right. Unfortunately, WordPress may already have done all the work required to build them.

Hidden after rendering

Block Logic currently uses WordPress’s render_block filter to remove blocks when their conditions aren’t met.

The problem is timing. The render_block filter runs after WordPress has rendered the block and its inner blocks. Block Logic removes the resulting HTML, but any dynamic rendering and database queries have already happened.

For an ordinary paragraph, this probably makes little practical difference. For a Query Loop or another dynamic block which performs several database queries, it certainly can.

The block is invisible. The workload isn’t.

Preventing the work

WordPress provides another filter called pre_render_block. As the name rather helpfully suggests, it runs before the block is rendered.

If Block Logic checks its condition there and returns an empty string for a hidden block, WordPress doesn’t run that block’s render callback. It also avoids rendering any blocks nested inside it.

We tested this using a dynamic block which recorded each time its render callback ran:

  • With render_block, the hidden block’s callback still ran.
  • With pre_render_block, it didn’t.
  • When a hidden parent contained a dynamic child, the child didn’t render either.

That is both the expected behaviour and the more efficient one.

We’ve reported the issue to the Block Logic developer. The existing render_block check could remain as a safety net, but adding an earlier pre_render_block check would prevent hidden dynamic blocks from doing unnecessary work.

Because if a block isn’t going to appear, rendering the whole thing first seems a little daft.

Comments …

Leave a Reply

Your email address will not be published. Required fields are marked *