Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use document.write?

I was wondering why ad's still use the document.write approach to inserting the add into the page

<script language="javascript" type="text/javascript">
    document.write("<script type='text/javascript' src='http://addomain/someadd.js'><\/sc" + "ript>");
</script>

Why is it that I can't just put

<script type='text/javascript' src='http://addomain/someadd.js'></script>

In place of the ad?

like image 925
James Hughes Avatar asked Feb 17 '09 11:02

James Hughes


People also ask

Is it good to use document write?

Since document. write() is always available (mostly) it is a good choice for third party vendors to use it to add their scripts. They don't know what environment you're using, if jQuery is or isn't available, or what your onload events are. And with document.

What is the use of write () method?

The write() method deletes all existing HTML when used on a loaded document.

What is the difference between document write and written?

write() writes to the document without appending a newline on the end. document. writeln() writes to the document appending a newline at the end.


2 Answers

A traditional script tag will block the page while it is loading and executing. A script loaded with document.write will work asynchronously. That's why you see this on ads or analytics, as such scripts don't influence the page content directly.

like image 154
Christophe Avatar answered Oct 10 '22 05:10

Christophe


I work with a web advertising company, and from what I've heard, certain browsers (don't know off hand which ones) will allow you to drop script tags into the page, but won't allow you to automatically execute their contents.

So, to pull this off, you need to break the script tag into pieces so the browser doesn't treat it as a script tag, but rather as any old HTML Data. Then, as the DOM is processed serially, the next thing it evaluates, after writing out the script tag is... hey, that script tag you just wrote out.

At this point the script tag is evaluated and executed.

like image 29
Paul Sweeney Avatar answered Oct 10 '22 05:10

Paul Sweeney