I'm rendering a custom JSF component. In the method encodeBegin I want to include some java script.
public void encodeBegin(FacesContext context) throws IOException {
ResponseWriter writer = context.getResponseWriter();
writer.startElement("script", this);
writer.writeAttribute("type", "text/javascript", null);
writer.writeText("var width=400",null);
writer.endElement("script");
}
When rendering the component the content of the script tag is commented out.
<script type="text/javascript"><!--
var width=400;
//--></script>
Can anybody explain why this comment appears and how I get rid of it?
Thanks in advance!
This is specific to the MyFaces implementation, not to JSF specification. The Mojarra implementation doesn't do that.
This approach of putting JavaScript body in a HTML comment is basically a leftover of the HTML prehistory back when browsers existed which doesn't support <script>
elements. Those HTML comments basically hides the JavaScript content to prevent those ancient HTML parsers from interpreting and displaying JavaScript code as plain text.
See also Mozilla Developer Network - Writing JavaScript for XHTML:
This was common practice in HTML, to hide the scripts from browsers not capable of JS. In the age of XML comments are what they were intended: comments. Before processing the file, all comments will be stripped from the document, so enclosing your script in them is like throwing your lunch in a Piranha pool. Moreover, there's really no point to commenting out your scripts -- no browser written in the last ten years will display your code on the page.
Note the last sentence, this is very true, no single browser developed in the last decade would do that anymore. MyFaces is apparently a bit overzealously assuming that one would still be using such a prehistoric browser nowadays.
It is ok
The practice is marking the javascript code as comments, so automatic tools don't try to parse it as HTML (for example, tools that check that your page is HTML 4 compliant).
The Javascript engine will ignore the HTML comment and process the code (Javascript comments are /*
and //
A variation of this approach is putting the Javascript inside a CDATA
tag, for the same reasons.
来源:https://stackoverflow.com/questions/15477025/custom-jsf-component-using-startelement-with-script-results-in-a-comment