Google Adsense and DOMContentLoaded events

Posted by Neil on 25th June 2007

Google's AdSense can really mess up handlers attached to the DOMContentLoaded event by making it seem as if elements have gone missing.

The problem seems to occur when you have elements in the document that are referenced by code in the event handlers. If the AdSense JavaScript is placed before these elements in the document, the DOMContentLoaded event can be fired prematurely before the DOM is fully loaded. If you are checking for the presence of your elements before operating on them (always a good idea), the handler will fail silently. If not, you can have an error thrown.

The issue does not arise on every load of the page, but seems to happen up to 50% of the time.

One workaround is to place the AdSense code later in your document, after your affected elements. This reduces the incidence of the issue, but may not entirely eliminate it.

It may be that the iframe loaded by AdSense may be incorrectly firing DOMContentLoaded events for its parent page. The investigation is ongoing...