the write stuff

Many a developer improving the front-end peformance of a site has found their way to a heavy drag on the site’s loading:

<div class="adblock">
    <script type="text/javascript">
    document.write('<scri'+'pt tpye="text/javascript" src="http://adnetwork.example/ad/mysite"></scr'+'ipt>');
    </script>
</div>

A fair number of naive but smart developers (myself included) have responded with, “document.write is serving no useful purpose on my site, I’ll overwite the function and figure out how to defer loading that script.”

And several brave developers have been lost down this path, finding the contents of the <script> to be:

document.write('<p><a href="http://adnetwork.example/click"><img src="someimage.jpg" /></a>');

One weekend in Philadelphia, a Tablet front end developer, Matthew Story, had enough and thewritestuff.js emerged. A js library that wrestles document.write and wins. Though not necessarily a good idea, this has been in use without (significant) issue on tablethotels.com for several years.

thewritestuff.js allows you turn this:

<div id="wrongstuff-block">
    <script type="text/javascript">
        document.write('<scr'+'ipt type="text/javascript" src="js/inconsideratead.js"></scr'+'ipt>');
    </script>
</div>

to this:

<div id="writestuff-block"></div>
<script type="text/javascript">
    Writes.waitingToWrite.push(function() {
        new Write('<scr'+'ipt type="text/javascript" src="inconsideratead.js"></scr'+'ipt>',
            document.getElementById('writestuff-block'));
});
</script>

Throw further <script>’s inside the document.write’s, and it still has the right stuff. And finally, the ability to target multiple dom elements.

It works by overwriting document.write, storing the strings sent to the function in an array that serves as a queue of “stuff to be writen”. Any <script> elements that would be written in one of these strings is appended to the targeted element, the result is captured and it’s place in the “stuff to be writen” to the targeted element is replaced by the output. When there are no more <script>s left, the string is finally written/appended to the original targeted element.

I’m entertained by the utility, ugliness, and uniqueness of this solution to a difficult problem. Cheers to entertaining javascript!

posted: 08/12/2011