Object Expected Error from Google Analytics Solved

I noticed that Google's analytics code was throwing a javascript error "Object expected" when hitting the site i Internet Explorer. Lots of googling show many other people with the same problem but, no solutions. Removing the code showed no javascript errors and the page validates (with the W3C) as XHTML trnsitional.

I also have Google Adsense on the site. It turns out the problem was a little nefarious. The line to include the ads:

  1. <script type="text/javascript"
  2.    src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
  3. </script>

This line was being collapsed by the Tomcat JSP compiler to:

  1. <script type="text/javascript"
  2.    src="http://pagead2.googlesyndication.com/pagead/show_ads.js" />

Since IE's parser isn't the sharpest in the box, it acted as if the tag was still open (notice the closing whack is actually in the tag). Then, when it came to the analytics tag:

  1. <script type="text/javascript"
  2.    src="http://www.google-analytics.com/urchin.js">
  3. </script>

It appeared to the browser to be part of the body of the other tag. The closing tag, acted as the closing tag for the ads. No script error was shown for HTML inside the script tag because it had a source attribute. The page validated because it was valid.

The solution, add a javascript comment inside both the ad's script tags and the analytics script tag.

  1. <script type="text/javascript"
  2.    src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
  3.   /* Google Ads */
  4. </script>

and

  1. <script type="text/javascript"
  2.    src="http://www.google-analytics.com/urchin.js">
  3.   /* Analytics */
  4. </script>


Sponsors:

About willCode4Beer