0

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.

3
  • Did you try the <c:if test="#{myBean.isRendered}"> jstl tag instead of the java code settings? Commented Mar 14, 2017 at 18:57
  • @TheBitman no. How is that helpful when creating a UIComponent? Commented Mar 14, 2017 at 19:49
  • I thought maybe you could filter js LINK in the JSF file instead of the component. But tell the truth I don't understand your question totally :) Commented Mar 14, 2017 at 19:53

1 Answer 1

0

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.