dracoblue.net

Why <!-- beats <![CDATA[ for inline javascript

I guess everyone knows, that using:

<script type="text/javascript">
  myMagicFunction("This & That");
</script>

is pretty bad practice. The issue is, that the & should be escaped and read as & instead.

If you are reading this code with an Ajax-Request and it contains for instance unescaped & character, it will fail to load the xml properly and also fail executing the embedded javascript.

The workaround I see pretty often is the following (even suggested by w3schools:

<script type="text/javascript">
<![CDATA[
  myMagicFunction("This & That");
]]>
</script>

a better way is of course:

<script type="text/javascript">
// <![CDATA[
  myMagicFunction("This & That");
// ]]>
</script>

because it does not break any backwards compatibility to browsers, who do not get the cdata tag when in non xml mode.

This solution has one big problem: This claims the inner content to be included at this point and be escaped automatically. And this valid html will be made visible to search engines.

Since I don't want anyone to count this comments as content for my website I am using the following solution for ages:

<script type="text/javascript">
// <!--
  myMagicFunction("This & That");
// -->
</script>

It works like a charm. If you are still using any of the previous solutions, please consider this solution as a replacement.

In html, javascript by @ 30 May 2010

comments powered by Disqus

Recent Files

Advertisement

Recent Dev-Articles

Read recently

About

Blogroll