Timo Ernst
Timo Ernst

Reputation: 15973

How to handle document.write()-based ad tags in a one-page web site?

I wrote a website for iPhone/Android build on top of jQueryMobile. This means that there are no page refreshes. Instead, all sites are rendered into one page and only the hashtag at the end of the URL changes and causes page transitions.

Now I wanted to embed JavaScript-based ad tags from one of our ad partners. This script code writes the ad (image or js-based ad) via document.write() into the site.

Example:

<script>
 for (var i in adTags){
  var adTag = adTags[i];
  var jscode = adTag.jscode; // Contains document.write() call in <script> Block
  var container = $("#" + adTag.containerId);
  container.html(jscode);
 }
</script>

The problem here is that, while document.write() works well on a static site with page refreshes, a one-page website gets completely destroyed because dynamic calls of document.write() after the HTML document was fully loaded, will empty the <body> tag.

Example:

Assuming my HTML looked like this before:

<html>
 <head>
  <title>Foo</title>
 </head>

<body>
 Hello World
 <div id="ad1"></div>
 <div id="ad2"></div>
</body>

</html>

After running the JavaScript code above, my body looks like this:

<body>
    <img src="http://www.adserver.com/foo.png">
</body>

As you can see, document.write() completely removes all the content of <body>. That's not tolerable.

So, I do I solve this problem?


Note: I already tried to work around this by overwriting document.write() like this:

<script>
 var currentContainer = null;

 document.write = function(code){
  currentContainer.html(code);
 }

 for (var i in adTags){
  var adTag = adTags[i];
  var jscode = adTag.jscode; // Contains document.write() call in <script> Block
  var container = $(adTag.containerId);
  currentContainer = container;
  eval(jscode);
 }
</script>

Now, while this works well at first sight, the problem here is that the AdTag's call of document.write() loads another piece of JavaScript which looks like this:

<script src="http://www.adserver.com/more.js"></script>

This js file contains another call of document.write() which would again call my custom (overwritten) document.write() function. The problem now is that in the meantime my for() loop has continued and changed the content of the variable currentContainer and then my custom document.write() function writes the new content into the wrong div container.

Upvotes: 0

Views: 645

Answers (1)

Timo Ernst
Timo Ernst

Reputation: 15973

I found that running the ad tag code inside an iframe is the best solution.

Upvotes: 1

Related Questions