What is the best way to ensure a component's client lib files only load on the page when the component is present?

1k views Asked by At

I'm new to AEM. Currently we have one template for each page on our site. All components have the category "project_name.components" and I am calling the client libs in a header file with:

<sly data-sly-call="${clientLib.css @ categories='project_name.components'}" />
<sly data-sly-call="${clientLib.js @ categories='project_name.components'}" />

However, I have a breadcrumbs component that isn't on every page, but, as expected, the client libs files for it are showing up regardless and causing some issues with the existing default breadcrumbs's styles/scripts.

I have given the new breadcrumb component a test category name of "project_name.breadcrumbs". Is there a way to use this category name in some type of an if/else statement in the same header file that will only call the breadcrumb client lib files if the breadcrumb has been dragged onto the page?

1

There are 1 answers

1
Shawn On BEST ANSWER

A few thoughts:

  • The easiest way is to include the client library as part of the component that uses it rather than including it somewhere else. The downside of this is that the CSS you may want to load early in the HEAD section of a page won't be present until somewhere in the BODY.
  • If your CSS styling is impacting things it shouldn't, then the CSS styling needs to have sufficient selectors so that it won't break things to which it shouldn't apply. Perhaps you can add a class to the breadcrumbs and make all the styling only be applied to stuff under a tag that has the class. If you changed the CSS this way, it wouldn't negatively affect pages when they don't use the breadcrumb (though it could have a downside of bloating your page footprint if it isn't something that will be loaded and browser cached to be used in the future).
  • Otherwise, you could add logic that runs at the page level that will examine the node and see which components are included and then add conditional logic to only add the client library when the page is using the component. But that is more back-end work. So you can add the if/else statement as you suggested, but it is up to you to write the code behind it--there is nothing built-in that will conditionally do that check to my knowledge.