When to use <! [CDATA [in Javascript

I saw some Javascript code containing CDATA. for example below which I copied 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> 

Please note that I made the description contained in the link above. However, I could come to a conclusion about when to use the CDATA tag.

If anyone can help me understand the purpose of this tag, and when to use it, that would be great.

+4
source share
3 answers

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

Note that if you are serving XHTML with Content-Type text/html , then it will be treated as broken HTML, not XML. I recommend avoiding XHTML - this is only useful if you have XML processors in your toolchain and manipulation to play well with HTML parsers, this is unnecessary work. Just write HTML and do with it.

+6
source

We can just say that we need a part of CDATA, we need your document for analysis in XML format

+3
source

CDATA does not make sense in HTML, but in XML it is used to process characters such as angle brackets and ampersands. I use the CDATA block when I need to include JavaScript in my XSL transforms.

Understanding what CDATA does is likely to help you figure out when to use it: "Some texts, such as JavaScript code, contain a lot of" <"or" & "characters. To avoid errors, script code may be defined as CDATA." See also: What is CDATA in HTML?

0
source

Source: https://habr.com/ru/post/1491841/


All Articles