Article Written

  • on 25.02.2009
  • at 02:03 PM
  • by admin
Feb25

CDATA Run. Run, Data, Run! 0 Comments

Have you ever viewed the source of someone else’s webpage and seen gibberish like this:

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

Looks crazy. When I first ran across it, I assumed it was a random comment left by a developer (meaningful only to him or her). But there’s actually a really good reason why you’ll want to use this code.

When you validate a page using the W3C Markup Validation Service, the < and > characters are important. As a document is parsed, the validator relies on these characters to let it know when it has reached a tag in your HTML code. The parser uses a page’s tag hierarchy to understand the structure of your page and to determine if anything is invalid.

So, when it stumbles upon a random < or > in embedded JavaScript, the parser will get angry and return an error. (Note: Inline, or embedded, JavaScript is any script that is included directly in your HTML. It’s always a better practice to use external JavaScript files, but in the cases where inline scripts are unavoidable, continue reading.) The parser thinks it is encountering the beginning or ending of a tag, when in actuality it may have found a logical greater or lesser symbol instead.

To prohibit the parser from encountering and evaluating code, like JavaScript, surround the code in the gibberish above. For example:

<script type="text/javascript">/* <![CDATA[ */... your code .../* ]]> */</script>

Now your JavaScript is untouchable and will not anger pesky validators. Check those errors off the list! (All of the other errors really are your fault, though. Lazy developer.)

Note: The comment characters /* and */ are not required, but failure to include them will cause some JavaScript compilers to freak out. Be safe, include them.