CSS splitting with blocks & snippets

Hi all - I’m trying to find the best way to split css into separate files for each block & snippet for better site performance. The catch is I want to achieve this without any compile trickery.

As far as I know I can’t just load the css at the top of a block/snippet as the css needs to be in the head of the site, so that just leaves me with having to check the current page for all blocks and snippets present and return the relevant css file.

Does anyone know the best way to do this and if in fact that is the best way?

Thanks!

In my opinion you should consider if this isn’t premature optimization.

If you want to proceed, one idea could be to output buffer the page to catch all css files that are required by “registering” them somehow in each block, then write out the css links before sending the buffered rest of the page.
If you have a header and a footer snippet you use on each page, you could add the logic there.

snippets/header.php

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>page title</title>
  <?php
    $cssFiles = [];
    function registerCss(string $path) {
      global $cssFiles;
      $cssFiles[] = $path;
    }

    ob_start(fn($buffer) => css($cssFiles) . $buffer);
  ?>
</head>
<body>

snippets/footer.php

<?php ob_end_flush() ?>
</body>
</html>

snippets/blocks/foo.php

<?php registerCss('assets/css/fooblock.css'); ?>
Foo Bar!
1 Like

Thanks, I was thinking something along these lines but you’ve fleshed it out better. You might be right about premature optimisation; in most recent projects I’ve worked out you’d be shot for not splitting stylesheets, so I’m used to wanting to do this, but in reality on the projects I’n using it for it may be overkill.