How to Use Per Page JavaScript with Conditional Includes in Slater
Slater enables per page JavaScript functionality through the use of conditional includes. This approach allows developers to load specific scripts or stylesheets only on designated pages, optimizing performance and ensuring maintainability.
Slater offers the ability to include JavaScript and CSS files on specific pages by leveraging conditional logic within your code. This feature is particularly useful for targeting functionality or styles to particular sections of a site without affecting others and improves your site's overall performance.
How Conditional Includes Work
Conditional includes use the current page's URL path to determine which scripts or styles to load. By checking the path, it's possible to import resources only when they are needed.
Example: Structure for Per Page Includes
let paths = window.location.pathname.split('/')
// Global CSS
{
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'https://slater.app/1234/2104.css?v=805038';
document.head.appendChild(link);
}
// Global JavaScript
import('https://slater.app/1234/51518.js?v=277861')
// About Page JavaScript
{
const pages = ["about"];
const path = paths[paths.length - 1]
const itemPath = paths[paths.length - 2]
if (
pages.includes(path) ||
pages.includes('detail_' + itemPath) ||
pages.includes(itemPath + '/item')
) import('https://slater.app/1234/2089.js?v=572321');
}
Implementation Steps
To implement per page CSS and JS, you should select the page(s) you want the code to run on when creating a new file. You can also later edit which pages your code runs on by selecting the Edit File Settings on the file settings tab.
How this works.
-
Split the URL path:
- Use
window.location.pathname.split('/')to get the segments of the current URL.
- Use
-
Define page arrays:
- List the page slugs where the scripts should be loaded (e.g.,
["about"],["features"]).
- List the page slugs where the scripts should be loaded (e.g.,
-
Check the page context:
- Compare the current path segment(s) to your page arrays using conditionals.
-
Dynamically import scripts or styles:
- Use JavaScript's
import()or create elements for CSS as needed.
- Use JavaScript's
Benefits of Per Page Includes
- Performance: Only necessary resources are loaded, improving load times.
- Maintainability: Code is organized and targeted for specific pages, reducing complexity.
- Flexibility: Easily add or update scripts/styles for individual pages without affecting the global site behavior.
Additional Resources
For more information on modern JavaScript dynamic imports, see MDN Web Docs: import()