views:

48

answers:

2

On a website I'm working on, I need to load a tracking script 10 seconds after the page loads. I found a snippet to do so, but I've hit a snag. After waiting 10 seconds, the page goes white. The URL doesn't seem to change, but the page is no longer visible and the throbber starts spinning.

Here's what I'm using to load the script:

function $import(src){
  var scriptElem = document.createElement('script');
  scriptElem.setAttribute('src',src);
  scriptElem.setAttribute('type','text/javascript');
  document.getElementsByTagName('head')[0].appendChild(scriptElem);
}

// import with a random query parameter to avoid caching
function $importNoCache(src){
  var ms = new Date().getTime().toString();
  var seed = "?" + ms; 
  $import(src + seed);
}

// 
// Tracker options go here...
//

setTimeout(function(){
    $importNoCache("http://tracking.code/url");
}, 10 * 1000);

Is there a better way to do this?

EDIT: I stepped through the code in Firebug, and the scripts works like it should. With Firebug's debugger off, it blanks the page as I described above.

+4  A: 

This would happen if the script calls document.write.

Can you show us the script that you're loading?

SLaks
It's loading this script:http://www.googleadservices.com/pagead/conversion.js
bluejeansummer
The script does call `document.write`.
SLaks
I guess for now I'll just load it with the rest of the page. I didn't know this about `document.write`. Thanks anyways.
bluejeansummer
+1  A: 

The code looks fine, so the problem is probably in the tracking code. If it contains a document.write() call, it will work fine when included normally, but wipe out the page when included after the page has finished loading.

Edit: Yep, the tracking script does d=document, then calls d.write() later on... you won't be able to include this script after the page has finished loading.

olooney