dsp_099
dsp_099

Reputation: 6121

How to deal with document.write in a script that's added after a page has loaded?

I'm in a situation where I need to add an advertisement script tag dynamically.

The ad itself is just a simple script tag with the src attribute pointing to the ad server. The actual code which is then ran is a 2-step ordeal:

First, there is a document.write(), like so:

document.write("<iframe id='lctopti2017041855' src='about:blank' style='visibility: hidden;' onload=\"this.style.visibility='visible';\" style='border: 0px; overflow-x: hidden;overflow-y: hidden; width: 100px; height: 400px;' width='100' height='400' scrolling='no' frameborder='0' allowtransparency='true'></iframe>");

Next, there is a:

document.getElementById('lctopti2017041855').src = 'http://www.reallylongurl.com/blah.php?whatever=whatever'

Now, it seems that running document.write() as the page is loading is fine; but I've discovered that if I took the same initial tag and popped it inside of $('#somediv').prepend(), for instance, it would overwrite the entire page.

Is there any way to deal with this? The iframe id and the subsequent ad urls are always dynamic, and generated when the initial script tag requests the javascript from the ad server. If the initial script tag had all the information I needed, I could simply switch out document.write with $('#anywhere').prepend() or something. How can I solve this, short of literally scraping the results of the initial script load and then working with the result?

Is there a way to stop document.write() from overwriting the page but instead only writing where it was called?

Upvotes: 10

Views: 10050

Answers (2)

mplungjan
mplungjan

Reputation: 177851

Here is something I have successfully done before

var oldWrite = document.write;
var wHtml="";
document.write=function(str) {
  wHtml+=str;
}
// load adcode
$('#somediv').prepend(wHtml);
// optionally reset
document.write = oldWrite;

This may fail if the adcode loads a script using document.write too. In that case use an iFrame since it will contain all the crap they can do

Upvotes: 14

aisensiy
aisensiy

Reputation: 1520

If the document is loaded, document.write will flush the whole page. So it should not be put in a function which will be called after document loaded.

If you want more action, i think you can change to some other method.

http://javascript.info/tutorial/document-write some infomation about document.write is shown here. Hope it can be helpful.

Upvotes: 0

Related Questions