Nil Pun
Nil Pun

Reputation: 17373

When to use a <![CDATA[ in 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.

Upvotes: 5

Views: 701

Answers (3)

Mentatmatt
Mentatmatt

Reputation: 525

CDATA has no meaning in HTML, but in XML it's used to handle characters such as angle brackets and ampersands. I use a CDATA block when I need to include JavaScript in my XSL Transforms.

Understanding what CDATA does will probably help you understand when to use it: "Some text, like JavaScript code, contains a lot of "<" or "&" characters. To avoid errors script code can be defined as CDATA." See also: What is CDATA in HTML?

Upvotes: 0

PSR
PSR

Reputation: 40318

Simply we can say , we need CDATA part we need your document to parse as XML

Upvotes: 2

Quentin
Quentin

Reputation: 943556

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.

Upvotes: 7

Related Questions