Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use a <![CDATA[ in Javascript

Tags:

javascript

I've some seen some Javascript code containing CDATA. e.g. below which I copied from http://www.w3schools.com/xml/xml_cdata.asp

<script>
    <![CDATA[
    function matchwo(a,b)
    {
    if (a < b && a < 0) then
      {
      return 1;
      }
    else
      {
      return 0;
      }
    }
    ]]>
    </script>

Note that I did a description contained on link above. However I could come to conclusion on when to decide to use the CDATA tag.

If anyone could help me understand the purpose of this tag and when to use it will be great.

like image 973
Nil Pun Avatar asked Jan 12 '23 21:01

Nil Pun


1 Answers

In XHTML the content of script elements is treated as markup. So < and & have their usual special meaning. A CDATA block tells the parser to treat the content as text instead of markup, so you can say if x is less than y without the < being treated as the start of a tag.

Note that if you serve XHTML with a Content-Type of text/html then it will be treated as broken HTML and not as XML. I recommend avoiding XHTML - it is only useful if you have XML processors in your tool chain and munging it to play nicely with HTML parsers is unnecessary work. Just write HTML and be done with it.

like image 179
Quentin Avatar answered Jan 24 '23 13:01

Quentin