Quantcast
Channel: HTML – The Wiert Corner – irregular stream of stuff
Viewing all articles
Browse latest Browse all 60

CDATA inside JavaScript or style section of HTML? They are for backward compatibility. Sometimes compatibility with ancient browsers.

$
0
0

As a back-end person, sometimes I wondered about CDATA in front-end HTML code was for, especially in JavaScript and CSS style elements.

[WayBackHTML vs. XHTML – WHATWG Wiki explains how to be compatible with XHTML, HTML, XML based tools and older browsers:

The following code with escaping can ensure script and style elements will work in both XHTML and HTML, including older browsers.

In both cases, XML ignores the first comment and then uses the CDATA section to avoid the need for escaping special characters < and & within the rest of the contents (with subsequent JavaScript comments added within to ensure the HTML-oriented code is ignored by JavaScript).

In HTML, older browsers might display the content without the content being within a comment, so comments are used to hide this from them (while modern HTML browsers will run code inside the comments). The subsequent JavaScript comment is added to negate the text added for the sake of XHTML.

The <style> requires the /**/ comments since CSS does not support the single line ones.

   <!---->
       ...
   //-->
   <style type="text/css"><!--/*--><![CDATA[/*><!--*/
       ...
   /*]]>*/--></style>

If not concerned about much older browsers (from which one is hiding the HTML) one can use the simpler:

   //
   <style>/*<![CDATA[*/
   
   /*]]>*/</style>

Also note that the sequence “]]>” is not allowed within a CDATA section, so it cannot be used in true XHTML-embedded JavaScript without escaping.

–jeroen

via:


Viewing all articles
Browse latest Browse all 60

Trending Articles