Sergio Mercado

Writing about Web Development.

How to Load Ads Asynchronously

| Comments

The Problem

Most ads come with document.write statements, and we all know what happens when we try to execute them after the page has been loaded.

The Solution

postscribe is a JS library that ensures the content is written as close to the way the browser would natively write the content with document.write/innerHTML, and it does it asynchronously!.

The Implementation

HTML:

1
2
3
4
5
<div id="ad"><!-- ad content will be written here --></div>

<!-- postscribe scripts -->
<script src="htmlParser/htmlParser.js"></script>
<script src="postscribe.js"></script>

JS:

1
2
3
4
5
(function (win) {
  var adCode = '<script>document.write("ad unit");</script>';

  postscribe('#ad', adCode);
}(window));

Simple, right?!