On my website I have as little templates as possible (since doing otherwise would kind of defeat the purpose of using a template). However, not every page uses the same (java)scripts, but I'm currently loading all of them in the head.
I'm thinking about loading just what is necessary for the current page, and lazy loading the rest, to minimize the use of bandwidth and speed up page rendering.
What would be the best way to do this? Because a lot of pages use the same template, so I can't set this via the template. Also I'd like to make the solution as automatic as possible (so not having to set the scripts requirements for each page by hand, which could open the door to mistakes).
Does anyone have any ideas on how to do this? Template variables maybe?
-
☆ A M B ☆
- 894 Posts
What I always do is create a cssTV in the head and a jsTV before the closing body tag that is included in all my templates then I use an output filter to render it if it's not empty, something along these lines:
[[*cssTV:!empty=`[[*cssTv]]`]]
[[*jsTV:!empty=`[[*jsTv]]`]]
Then you can insert your additional css or js files per page.
Good luck, hope that helps.
Depends on the scripts, but not all of them need loading in the head, so sometimes you can load them into the same chunk you are using for the output or whatever else you are doing.
It would be easier if you could tell us what sort of scripts, and how many different sets of scripts you're loading on different pages.
Are these all different plugins or just custom js code for on-page elements?
You can also create an @INHERIT TV called JsFiles with a comma-separated list of the JS file paths. Then put a snippet like this in the template:
$files = $modx->resource->getTVValue('JsFiles');
if (! empty ($files)) {
$jsFiles = explode(',', $files);
foreach ($jsfiles as $file) {
$modx->regClientStartupScript($file);
}
}
That will put the JS links in the head.
You can also use regClientScript() if you want the JS at the bottom (just above the closing body tag).
Theoretically, you could skip the TV and analyze the page (e.g., with strpos() ) to calculate which JS files to inject.
I'd use a checkbox TV. If you can come up with short names for the scripts, you can do the Input Option values like this:
Script1==/full/URL/of/script1||Script2==/full/URL/of/script2.js||Script3==Full/URL/of/script3.js
-
☆ A M B ☆
- 24,524 Posts
Probably better to have the checkboxes load a chunk with the full set of tags. If these will require specific .css files as well, a snippet using regClientCSS(), regClientStartupScript() and regClientScript() might be a better choice in the chunks since that way the files can be loaded where they are wanted.