javascriptvalidationcdataw3c-validation

Why isn't CDATA protecting my javascript code from the HTML validator?


I inserted some js code (provided by a third party service) in my webpage and it broke my html validation. How can I fix the problem? CDATA isn't doing the trick. This is my sample snippet:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head>
  <title>test</title>
  <script type="text/javascript">
  /*<![CDATA[*/
    document.write('<script src="//sharebutton.net/plugin/sharebutton.php?type=horizontal&u=' + encodeURIComponent(document.location.href) + '"></scr' + 'ipt>');
  /*]]>*/
  </script>
</head>
<body>

  <p>test</p>

</body>
</html>

And here you can find the result of the validator.


Solution

  • <![CDATA[* is a feature of XML, not HTML. It is just part of the text content of the script element in HTML terms.

    To safely include the string </script> in a JavaScript string literal in HTML: Escape the slash:

    '"><\/script>')