Load js files only on a specific page

I have a page called ‘Books’ and I want to load two js files in the header plus jquery only when that page is selected. The js files are located at ‘assets/js/file1.js’ and ‘assets/js/file2.js’.

I have a snippet called ‘booksjs.php’, which contains:


<!-- Tablesorter -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="assets/js/tablesorter.js" type="text/javascript"></script>
<script type="text/javascript" src="assets/js/readListTable.js"></script>


Any advice appreciated.

If the page has a specific template, you can use the js() helper

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

For this to work, you need to put the js file into a folder with the same name as the template, see the docs: https://getkirby.com/docs/cheatsheet/helpers/js, Autoloading template specific script files

Otherwise, use an if statement.

I’d suggest to concatenate those files, though, to reduce the number of http requests.

Thanks, Texnixe.

Afraid my php/js knowledge is poor. I tried this:

` <?php if($page->uid() == ‘books’) {

echo snippet('booksjs');

} ?>
which doesn’t work. There is no books template. It just uses the default page template.

Don’t echo the snippet.

if($page->uid() == 'books') {
} ?>
1 Like

Many thanks. That works

By the way it’s generally recommended to load scripts after the content rather than in the <head>, because when the browser sees a <script> tag it will wait until the script is loaded and executed before rendering the HTML content that comes after.

If your script mostly does enhancements to your HTML (like adding a sorting capability to a table), it’s probably a good idea to add the script tags around the end of your content (for instance, before the </body> tag).

1 Like