views:

74

answers:

4

Considering the negative effects of document.write(), why are most tracking/marketing tags written using document.write()?

I've thought about it quite a bit, and the only respectable idea I've come up with is that by writing it client side, we're guaranteed the browser won't try to cache the resource. Is that it? Any other ideas?

+1  A: 

I don't see that this method guarantees anything when it comes to browser cache...? If it requests an image, for instance, the browser might still elect to serve that image from cache, regardless of whether the request originates from an IMG tag in the original source, or a document.write-written IMG tag.

My best guess is that they want the script to be self-contained and easy to deploy. A lot of the times (and for obvious reasons) the script referenced (eg. the URL to which the image points) is different depending on whether or not the current page is loaded over a secure HTTPS connection. If the current page is a https-page, load https://omniture.com/xxx, otherwise, load http://omniture.com/yyy. That's very easy to achieve in javascript, but you cannot hard code it in HTML. Given any server side language, it'd be equally easy to achieve, and that would be preferable, but I figure they don't want to say "go on and implement this functionality in whatever way you prefer", but rather, they want to deliver a solution that works as well as possible, regardless of the environment, and with as few dependencies as possible.

David Hedlund
A: 

It has nothing to do with cache. It has to do with the script provider not knowing where in the document the script was placed. The script provider can't just do document.getElementsByTagName("script") and insert HTML after the first script tag with a matched URI, as it doesn't know if the URI contains a hash (http://example.com/blah.js#foo) or was hosted directly on the first-party server to lessen DNS requests. There is a workaround, but it involves using the dark magic from script file names exposed in caught errors. An implementation of this magic can be found in my implementation of document.write for asynchronous scripts. (<script async>)

Eli Grey
A: 

It's definitely ugly, but it's about the most battle-hardened, dumbed-down, idiot-proof method there is. The paradigm of "write this content onto the page right here" leaves little room for surprises, and the implementation works reliably at least all the way back to v3 browsers, possibly earlier.

[edit] "v3" browsers, not as in Firefox 3, but as in Netscape 3. If Netscape still existed today I suppose it would be at version 11 by now.

greim
A: 

Scripts that are inserted into the page using document.write do not block other script execution so the page load speed is not impacted when external resources for ads are inserted into the page. More info here: http://www.stevesouders.com/blog/2009/04/27/loading-scripts-without-blocking/

davejohnson