0

I am trying to use some Facebook code in one of my pages.

The code is:

<script type="text/javascript">(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=000000000";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

However when I try to validate this as an XHTML+RDFa page I get an error. The error is caused by the & sign in this part "xfbml=1&appId". The WC3 validator recommends using:

&amp;

even in urls it says.

However, when I change the ampersand sign to:

&amp;

The script no longer works.

Is there a way to get this to work correctly and still validate?

Sherwin Flight
  • 2,345
  • 7
  • 34
  • 54
  • 1
    That's what a character data section (CDATA) is for; see also: [When is a CDATA section necessary within a script tag?](http://stackoverflow.com/questions/66837/when-is-a-cdata-section-necessary-within-a-script-tag) – miku Apr 05 '12 at 04:39

2 Answers2

2

You should be able to get it to validate by wrapping the code in a CDATA tag, like so:

<script type="text/javascript">(function(d, s, id) {
//<![CDATA[
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=000000000";
  fjs.parentNode.insertBefore(js, fjs);
//]]>
}(document, 'script', 'facebook-jssdk'));</script>
rjz
  • 16,182
  • 3
  • 36
  • 35
2
<script type="text/javascript">
/*<![CDATA[*//*---->*/
(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=000000000";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
/*--*//*]]>*/
</script>

Much of JavaScript will not be interpreted correctly by the XHTML parser. You need to escape it with CDATA.

AlienWebguy
  • 76,997
  • 17
  • 122
  • 145