I need to override document.write in order to render an ad that comes back wrapped in that function from google's doubleclick. Since the standard document.write replaces the page content entirely, i overrode it to append the contents of the ad to an existing element. However, I want to make sure that this override only occurs during the ad render and that any other document.writes that may be on the page are unaffected. Can this be scoped or accomplished via closure? I'm not very familiar with how that is done.
So far I have:
(function(){
function RenderAd(adURL,Element)
{
document.write = function(adContent) {
Element.append(adContent);
}
$.getScript(adURL);
}
RenderAd('http://ad.doubleclick.net/N4890/adj/za.za.home/main;pos=300top;tile=2;sid=Amazon;sz=300x250;ord=12247707435800953?',$('#HeaderDiv'));
}(document.write));
But when I call document.write('test');
afterwards, it is still using my version of document.write.
document.write is scoped within an HTML document so if you change it, any subsequent call to it will also execute the overwritten version. You could try something like storing the original document.write function in a temp var, overwritting it and then replacing it after you've completed the function call, however since the call to document.write is through a callback and is async, and since you're probably loading multiple ads on a page this way, you can't predict when you should restore the original document.write.
What's typically done in a scenario where a service call returns HTML wrapped in a document.write() call is to load that in a separate iframe, which will have its own document object.
So if you can, create an iframe for each ad and load the returned data from your call to Google's doubleclick into the iframe. the document.write will create a buffer just for that iframe and won't affect the parent HTML.
Use an iframe to place the ad. That way, you don't have to override the document.write. The ad would render on its own iframe and will not mess with the main page's document.write.
Another solution considered:
1. save original document.write in a variable
2. override document.write to your version
3. restore original document.write in $.getScript success callback.
But that would not work, as the callback is not fired after the script has executed.
Welcome to try https://github.com/shenjunru/LazyWrite
It allows you to control the document.write().
Hope it can solve your problem. Any question is welcome.