Skip to content
Advertisement

Dynamic Ad script Replacing Page

I have an application that uses a mobile ad provider; the way ad provider works is that I make a request on the server side, the provider returns me the mark-up and I include that on my site.

In order to make the load page faster (which is a requirement that I don’t control), I have an AJAX call to my server which then makes the call to the server side, returns the markup and I include the markup on my mobile view.

Most of the time, the markup I receive is a <img> or something similar.

However, when I receive a ad markup with <script> that make another call dynamically to receive the ad, the markup I receive from the dynamically loaded <script> ends up replacing the entire view; leaving with me just the ad.

I have tried a few things around it but haven’t been successful so far. Is there anything I can do make sure the dynamically received markup doesn’t end up replacing the entire page contents?

Advertisement

Answer

The problem is probably because the ad uses document.write as it’s output.

document.write is recklessly dependent on timing. If document.write is called before the onload event, it appends or inserts text into the page. If it is called after onload, it completely replaces the page, destroying what came before. – crockford.com

What you can do is to temporarily overwrite the document.write method. It is as simple as that:

// overwrite document.write with a custom function
var old = document.write;
document.write = function ( html ) {
  document.getElementById("target").innerHTML += html;
};

// ad code goes here, calling
// our document.write sandbox
document.write("<div> advertisement </div>"); 

// restore standard document.write
document.write = old;

You can see a little demo here.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement