Skip to main content
NOTICE

Add custom JavaScript

Ontario.ca Frontend projects can accept custom JavaScript files to make projects more dynamic and interactive. Custom JavaScript can be used for tasks like validating forms, fetching data, or updating UI content without reloading the page.

Create a custom JavaScript file

Ontario.ca Frontend projects contain a js directory in the the assets folder (src/assets/js) to store custom JavaScript files. It includes an empty script.js to get you started – you can add your code to this file or, depending on how you want to organize your project, create a brand new *.js file.

js/custom.js
document.addEventListener('DOMContentLoaded', function () {    // Your custom JavaScript code goes here    console.log('Custom JavaScript loaded!');});

Link the JavaScript file in a layout template

Create a new script tag in the _head_custom.njk file in src/_includes/app directory to add your custom JavaScript file to your project's pages. (A tag for js/script.js is already created by default.)

src/_includes/app/_head_custom.njk
<script defer src="{{ templateGlobals.assetsRoot }}/js/custom.js"></script>

Make sure to replace custom.js with the correct name for your custom JavaScript file. Including {{ templateGlobals.assetsRoot }} in the path to the file ensures it is loaded from the assets directory.