Template specific Javascript/CSS

I’ve been working on a website and I’m taking performance very seriously, considering mobile networks in Brazil are slow at times. Right now the home page is below 150kb and loads really fast (I’m caching pages with Memcached and gzipping with Nginx).

I needed to add some Javascript libraries (almost 100kb) to only 2 specific pages but didn’t want to add more weight to the home page. Previously I’ve done this by checkin the page slug on the footer, this time I found a cleaner solution: passing a variable to the footer snippet:

<!-- template/search.php -->

<?php snippet('footer', ['scripts' => [
  'assets/js/vendors.js',
  'assets/js/search.js',
]]) ?>
<!-- snippet/footer.php -->

  <?php echo js('assets/js/main.js') ?> <!-- loads on every page -->
  <?php if (isset($scripts)) echo js($scripts) ?>

</body>
</html>

The same principle can be applied to stylesheets.

2 Likes

You could also use this:

Autoloading template specific css files

<?php echo css('@auto') ?>

Template specific css files must be located in /assets/css/templates and named like the template.

2 Likes

Totally missed that, and looking at the source code it works for scripts too. Thanks for sharing!

This does not answer your question precisely but maybe it serves your purpose?
Art directed pages: https://getkirby.com/docs/solutions/blog/art-directed-blog-posts