Programming Tips #7 “XHTML Analytics”

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

programmer

Next up on my programming tips series we have another guest post. This one is written by Jonathan Holland.

XHTML Analytics

Most analytics packages include a snippet of javascript that you have to add to your page. Nearly all of them rely on using document.write to embed a dynamically generated remote call to their javascript files.

However, using document.write does not work correctly on XHTML markup and is in general a bad practice.

The code below shows a way to dynamicly include a script file in your page without relying on document.write:

var scriptSrc = "SomeUrl.js";
 
// Dynamicly Create a Script Node
 
var scriptTag = document.createElement('script');
 
scriptTag.setAttribute ('src', scriptSrc);
 
scriptTag.setAttribute ('type','text/javascript');
 
// Get a reference to page header
 
var head = document.getElementsByTagName('head');
 
if (head.length > 0) {
 
// Add the dynamically created Script Node to the header.
 
head[0].appendChild (scriptTag);
}

This can be used for google analytics, webtrends, or doubleclick. It allows you to have valid code in your page, and still call to their analytics packages.

-

If you have any programming tips that you would like to share with my readers please send them in via my contact form. I will be picking a ‘best tip’ which will be rewarded with a license for Zend Studio Professional.

There Are 6 Responses So Far. »

  1. Why is he smiling? JavaScript doesn’t make developers smile.
    Nevertheless, good tip.

  2. While I agree that document.write() is in general a very bad practice, I wanted to point out that PPK described how to use it, to ensure that pre-hidden content does not accidentally show visibly as the page loads…

    http://www.quirksmode.org/blog/archives/2005/06/three_javascrip_1.html#link4

  3. JavaScript is a very nice language to work with if you are following best practices and understand JS fundamentals.

    Also you may consider JSON Remote Loader project http://www.sergeychernyshev.com/javascript/remoteloader/ if you need to fetch cross-domain data.

  4. [...] first, tip #7, was written up by Jonathan Holland. He talks about a method of using metrics software that works [...]

  5. hot horny black teens…

    hot horny black teens…

  6. cartoon sakura from naruto naked…

    cartoon sakura from naruto naked…

Post a Response