Forum Discussion

ykhaburzaniya's avatar
4 years ago

Adding freemarker to head from within a component

I have some custom components that need external javascript libraries.
For performance reasons, I want to start downloading the library when <head> tag renders, but the component that needs the js library is deep down in the component hierarchy.
At this time I have to resort to putting <script> or <link preload> or <link preconnect> tags in the head and then execute the javascript in the component.

Ideally I would want the component to contain all the code that is required for it to work including download/preloading/preconnecting scripts. Is that at all possible?
 
Note: Using javascript in the component to dynamically add the <script> tag in the <head> doesn't solve the problem because it will start download only when parsing html body. Placing it early in the download queue results in a performance boost, but the only way to achieve that is to have the <script><preload><preconnect> tags in the <head> come from the server side. (as far as I know).

Khoros Communities 

  • NilsD's avatar
    NilsD
    Khoros Staff

    The problem is that when the head gets rendered (where you rightfully would need the preloads etc.) we do not yet know if the page coming up will contain your component. So we cannot make that distinction. What you are effectively asking is: Can I modify the whole DOM from within a component on the server-side. It's an interesting thought, but this does not seem to be possible as the component is a self-contained element. It also conflicts with the Freemarker logic as that is that of a mere templating language.

    What would be possible (to get everything into the component itself) is that you could have a parameter that you pass into your component and with that set, you only render the head/preload/.. tags. Then you can call your component from within the head_top component. At least that moves the logic out of there. What remains is to scope this only to the pages where this gets used - and THAT is not possible automatically, thus the component rendering call in the head_top would need to guarded by something like <#if page.name == FroumTopicPage> given you use your component there. That is the best we could do. We just do not know at that point in time if this is needed or not.

    • I was hoping that maybe some hooks could be used similar to <#nested> and <@delegate> put together with some sugar on top. For example, if I mark a spot in my template's head as <@head_content append=true />, and then individual components would provide <@head_content>abc</@head_content> in order to append more code to the head tag. I have seen this technique in other templating languages, but I if it is not possible, will have to figure out how to make it work as smooth as possible in Khoros+freemarker