Including JavaScript in HTML content

For the last couple of days, I was struggling with Java ServerFaces. The exact problem was, that commandButtons were working as expected, but commandLinks were not. We are using Apache MyFaces with Tomahawk and Sandbox components. We were going to use commandLinks for navigation and other uses like selecting nodes in Tomahawks’ tree2 component, but we were forced to render commandButtons instead, which looked quite awkward in some places.

Symptoms we got, were that three browsers: Firefox, Opera and Konqueror, were complaining about “oamSubmitForm is not defined” after clicking a commandLink. Google wasn’t really helpful as it seemed, that no one was ever struggling with that sort of problem. I used Firebug (great Firefox extension for web developers, grab it here) to check what really Firefox was getting from a server and what really was the code it was rendering. And there was something not right, MyFaces rendered JavaScript code, that included “oamSubmitForm” function, but Firefox couldn’t find it. When I looked at what Firefox was really rendering (HTML tab in Firebug), there were two blocks of JavaScript, but both empty. I Googled a little more and stumbled upon some posts regarding JavaScript code included in a page, which content type was application/xhtml+xml. I checked what content type I was getting from my server, and it was text/xml. When I’ve added <jsp:directive.page contentType="text/html; charset=UTF-8"/> to header of my page, suddenly all commandLinks started to work correctly.

What happened? A good practice is that when you include JavaScript code in your HTML page you should use comment out all this code using HTML/XML comments: <!-- and -->. That’s enough when your content type is not something like text/xml. In that case, you need to write all JavaScript code within CDATA block so it should look like this:

<script type="text/javascript">
<[CDATA[
 // your code here
]]>
</script>

Apparently, MyFaces doesn’t do that. I’ll confirm that, and if that’s true I’ll report a bug and provide a patch. So keep up, I’ll tell you when that will happen, and post this patch here also.