Search code examples
jsfresourcesuicomponents

JSF resource (JavaScript) not rendered using addComponentResource


I'm on Mojarra 2.2.13 and my project uses PrimeFaces 6.0.

I'm writing my own JSF UIComponent. It requires a bit of JavaScript located in webapp/resources/js/charts.min.js. When I annotate my component using @ResourceDependency the script is rendered:

@ResourceDependency(name = "js/charts.min.js", target = "head")

But, I don't always need it to be rendered. So I was trying to conditionally add a component resource to the view root from within the encodeBegin(FacesContext context) method:

if (condition) {
  UIOutput js = new UIOutput();
  js.setRendererType("javax.faces.resource.Script");
  js.getAttributes().put("name", "js/charts.min.js");
  context.getViewRoot().addComponentResource(context, js, "head");

  writer.startElement("div", null);
  writer.writeAttribute("class", "myChart", null);
  // ... write chart data
  writer.endElement("div");
}

This does not render the script (myChart is rendered though). No errors appear in my log. Any ideas what I could check or improve?

I've also tested without PrimeFaces (not sure if its head renderer was causing this), but the result is the same.


Solution

  • So, encodeBegin(FacesContext context) is not the correct location to add resources. You are too late there.

    I've moved the code to the constructor of the component and now the script is added. I'm not 100% this is the best location to do so, but I've seen component libraries doing it in the constructor as well. It also works together with PrimeFaces.

    See also: