Cassie Meharry
Cassie Meharry

Reputation: 2683

Javascript delayed loading blanks page

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.

Upvotes: 1

Views: 523

Answers (2)

olooney
olooney

Reputation: 2483

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.

Upvotes: 1

SLaks
SLaks

Reputation: 887275

This would happen if the script calls document.write.

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

Upvotes: 4

Related Questions