Component specific ClientLibs? | Community
Skip to main content
New Participant
May 2, 2018
Solved

Component specific ClientLibs?

  • May 2, 2018
  • 14 replies
  • 12120 views

Hey folks,

I haven't seen a way to do this, but is there a way to load CSS/JS in your <head> conditionally when a specific component is on page?

The use-case is that we have a component with quite a bit of CSS/JS that is ONLY used on a given page or two, so rather than load that CSS/JS everywhere, we only want to load it when that component is on-page.

I'm sure I could query the page I'm on and see if the component is on page, but I was wondering if there's a more performant/built in way to do this.

Thanks!

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by joerghoh

By default this is not possible. The standard rendering process starts from the top of the page and all generated markup is immediately written to the output buffer, and then sent to the client. That means at the point when you reach your component the header is already written and comitted.

The only way to achieve this is to intercept that behaviour. Use a filter and buffer *all* data written to the output buffer in memory. Then you can render safely all components and if you encounter your special component you can set a flag in the request attributes. The filter can then check for these attributes, change the buffer accordingly and then send everything out.

That approach is a bit risky, because it *can* consume a lot of memory. And it changes the rendering performance and behaviour of your page. But it might be worth a try.

Jörg

14 replies

VeenaVikraman
New Participant
May 2, 2018

I would like to agree with scott and rima. I had tried this few times but could neva figure out a solution . As of now my answer would be no.

smacdonald2008
New Participant
May 2, 2018

There is no way to put a client lib - say in a page header and have it only load if a certain component is dropped onto the page. As Rima suggested - if you only want a clientlib to load for a specific component - add the HTL synatx to the component -- ie:

<sly data-sly-use.clientlib="/libs/granite/sightly/templates/clientlib.html" data-sly-call="${clientlib.css @ categories='bannerComponent'}"/>

Also - make no difference if call is made in body to head - it still gets loaded either way. In other words - if you only need a specific Clientlib in a component - no advantage to load it within the head section.

New Participant
May 2, 2018

I don't think that's exactly what I want because then the JS/CSS would be in the page body where the component is, and not in the <head>.

Rima_Mittal
New Participant
May 2, 2018

Why don't you have a specific category for the component clientlibs and include the clientlibs in the component jsp/html file itself?