JavaScript - controlling the insertion point for document.write

Yoav Weiss picture Yoav Weiss · Oct 8, 2009 · Viewed 12.7k times · Source

I would like to create a page that runs a 3rd party script that includes document.write after the DOM was already fully loaded.

My page is not XHTML. My problem is that the document.write is overwriting my own page. (which is what it does once the DOM was loaded).

I tried overriding the document.write function (in a way similiar to http://ejohn.org/blog/xhtml-documentwrite-and-adsense/) but that doesn't cover cases where the document.write contains partial tags.

An example that would break the above code is:

document.write("<"+"div");
document.write(">"+"Done here<"+"/");
document.write("div>");

Is there some way to modify the document.write insertion point through JavaScript? Does anyone have a better idea how to do this?

Answer

noah picture noah · Dec 29, 2009

If you're dealing with 3rd party scripts, simply replacing document.write to capture the output and stick it in the right place isn't good enough, since they could change the script and then your site would break.

writeCapture.js does what you need (full disclosure: I'm the author). It basically rewrites the script tags so that each one captures it's own document.write output and puts it in the correct place. The usage (using jQuery) would be something like:

$(document.body).writeCapture().append('<script type="text/javascript" src="http://3rdparty.com/foo.js"></script>');

Here I'm assuming that you want to append to the end of the body. All jQuery selectors and manipulation methods will work with the plugin, so you can inject it anywhere and however you want. It can also be used without jQuery, if that is a problem.