In JSF 2.0, you can use <h:outputScript /> tag to render a HTML “script” element, link it to a js file in the page. For example,

JSF…

<h:outputScript library="js" name="common.js" />

HTML output…

<script type="text/javascript" 
  src="/JavaServerFaces/faces/javax.faces.resource/common.js?ln=js">
</script>

JSF outputScript example

An example to show the use of JSF 2 <h:outputScript /> to render a “common.js” file in the “resources/js” folder, see figure below :

jsf2-outputScript-example

JSF file

<?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:h="http://java.sun.com/jsf/html"
      >
    <h:head></h:head>
    <h:body>
 
    	<h1>JSF 2 outputScript example</h1>
 
    	<h:outputScript library="js" name="common.js" />
 
    </h:body>
</html>

It will generate the following HTML output

<?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">
 
   <head></head>
 
   <body>
 
     <h1>JSF 2 outputScript example</h1>
 
     <script type="text/javascript" 
       src="/JavaServerFaces/faces/javax.faces.resource/common.js?ln=js">
     </script>
 
   </body>
</html>

The JS file will render in where JSF <h:outputScript /> tag is placed.

“target” attribute
In addition, you can use “target” attribute to render js file within the head element like following :

<h:outputScript library="js" name="common.js" target="head" />

It will generate the following HTML output

<?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">
 
   <head>
     <script type="text/javascript" 
       src="/JavaServerFaces/faces/javax.faces.resource/common.js?ln=js">
     </script>
   </head>
 
   <body> 	
     <h1>JSF 2 outputScript example</h1>		
   </body>
 
</html>

Download Source Code

Download It – JSF-2-outputScript-Example.zip (9KB)

Reference

  1. JSF <h:outputScript /> JavaDoc
Note : You can find more similar articles at - JSF 2 Tutorials