Search code examples
javascripthtmlmatomonoscripthtml-head

Piwik tracking code breaks HTML Validation


I'm using Piwik to track visitors to my blog. Here is the Piwik tracking code:

<!-- Piwik -->
<script type="text/javascript">
  var _paq = _paq || [];
  _paq.push(["setDomains", ["*.example.com"]]);
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
    var u="//example.com/pwt/";
    _paq.push(['setTrackerUrl', u+'piwik.php']);
    _paq.push(['setSiteId', '1']);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
  })();
</script>
<noscript><p><img src="//example.com/pwt/piwik.php?idsite=1" style="border:0;" alt="" /></p></noscript>
<!-- End Piwik Code -->

They recommend to paste that code immediately before the closing </head> tag.

So I've added the code and it works fine, but I just noticed that it is breaking my HTML Validation. Basically, it does not like the <p> or <img> tags being in the page head. Should I move the entire <noscript> section to the page body? Will that break my tracking for people with Javascript disabled? Why does an HTML Validator complain if the <noscript> section won't even been seen by browsers with javascript disabled.

Thanks!


Solution

  • You are right that <p> and <img> tags aren't allowed in the page head. Of course the HTML validator should complain. It doesn't know if your visitors will have scripting enabled or not.

    I would move the entire <noscript> section before the closing </body> tag. The way that section works, is that if someone has JavaScript disabled, it loads a small invisible image instead. Piwik records this image being loaded as a visit (note that the image source is a Piwik PHP script).