0

I need to conditionally include a couple of JavaScript files. Some are stored locally in my webapp, but one is loaded from an external site. The JSF page has a few sections surrounded by <h:panelGroup rendered="...">, and one of the sections needs the scripts, but the scripts rely on a part of the section to exist, otherwise they create errors. So I need to include the scripts only when the rendered condition of the corresponding section is met.

  • <h:outputScript> will only work for local files, so I need to use <script> for the external one.
  • All files must be loaded in , so I can't put a <h:panelGroup rendered="..."> around them
  • The local files are provided by someone else
  • No JavaScript file needs to be loaded dynamically ... it's "all or none"
  • The external file must be loaded before any local one, so the solutions from How to include an external javascript file conditionally? or Dynamically load a JavaScript file either won't work at all or are unnecessarily complicated

Edit:
As proposed by Jasper de Vries, I've tried putting a <c:if> around my <script> tags. I've ended up having two <head> sections in the rendered page. The second <head> (containing the <script> tags) was within the <body> and therefore the scripts were not loaded.

This how I tried it:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:c="http://java.sun.com/jstl/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">
<ui:composition>
<h:head>
  <c:if test="#{myUIBean.includeScripts}">
    <script type="text/javascript" src="..."></script>
    <script type="text/javascript" src="..."></script>
    <script type="text/javascript" src="..."></script>
    <script type="text/javascript" src="..."></script>
  </c:if>
</h:head>

<h:body>
   ...
</h:body>
</ui:composition>
</html>

Any ideas for a simple solution?

0 Answers0