The crux with online advertising
This problem leads to amazing workarounds, like loading the ad in an iFrame. Unfortunately, the iFrame does not know what kind of content the ad-supplier is going to provide at some point. "Context sensitive" iFrames are called for, which can adapt to the external content's size. A simple and efficient jQuery method is the following:
iFrame size is simply checked every x seconds (every second in this example). Since it is impossible to determine correctly, easily and rapidly - and working in every browser - the moment when an iFrame has finished loading its content, this is a legit solution, which of course only makes sense when you have just a few of those iFrames on your page (apart from the fact that iFrames are "naughty" anyway).
Rescue is at hand: just overwritedocument.write(). If it were indeed that easy, I would have done it myself, resp. there would have been functional solutions on the web a long time ago. There is evidence that for several years, developers have struggled with such a solution for all current browsers. It took me a while to find it, but the solution does exist, somewhere out there on the net. Newsweek.com baptized it the "Jesus script". This may seem a bit lofty, but it's okay because it works and it saves a lot of trouble:
Problems just occur when the externally loaded ad-scripts depend on theloadevent, because writeCapture interceptsdocument.write()instructions and executes them after the DOM has been established. But that will never happen, since theloadevent has already passed. The day is saved by the call-back functionality of writeCapture, which can trigger thewindow.load()event once more.