3

Currently I have all page scripts in site.js and passing it through apostrophe-assets like this:

module.exports = {
  stylesheets: [...],
  scripts: [
    {
      name: 'site'
    }
]

How can I pass some server/client-side js code to a specific page type?

antonys
  • 45
  • 4

1 Answers1

4

Currently Apostrophe doesn't specifically provide a way to do this. Surprisingly, it's not a terrible idea to just add a script tag to the page template. You can load it at the end of the body tag by overriding the extraBody nunjucks block in your page template:

{% block extraBody %}
  <script src="/modules/my-module/js/special-page.js"></script>
{% endblock %}

Due to the way Apostrophe provides symbolic links to each module's assets, this path will find the file here:

lib/modules/my-module/js/special-page.js

The reason this is not terrible is this: the .js assets you push to Apostrophe are minified and sent together on every page... which means the browser caches them. But if there are separate asset "scenes" for every page type, then minifying them all together would require a separate minified "big fat .js file" for each page type, and there would be no caching benefit when moving between pages of different types.

So allowing Apostrophe to minify the stuff you always/nearly always use, and separately sending the stuff you rarely use, turns out to be a win a lot of the time. You keep the universal stuff from your cache and get just a little bit of custom stuff for the specific page type.

Of course if you write a script tag like this Apostrophe doesn't minify the .js file for you. You can address that by using your own gulp workflow to build the .js file, which is not uncommon anyway for project specific code if you're eager to use ES6 features cross-browser.

See also:

Incorporating gulp to compile js in apostrophe?

But consider this... once you realize the user is going to visit several types of pages in a site visit, it's not a big step to deciding you should just push it all together and let Apostrophe minify it all together. The exception should be when the special payload for one page type is really, really large and the user probably won't visit that page in most site visits. In that edge case, we've been known to follow this technique too. Apostrophe itself relies on ckeditor's dynamic loader to avoid pushing all of the ckeditor rich text editor code on every login.

Tom Boutell
  • 7,281
  • 1
  • 26
  • 23