title: Speeding up external banner ads with asynchronous loading or caching
body: <p>I have a beautifully slick and elegant website that loads in double quick time, until of course the banner ads are enabled! Waiting to retrieve the adds up to 10 seconds on the the page load time which for me is really frustrating as I have spent ages optimising the rest of the site. </p>
  
  <p>I have tried to load the adverts via ajax or similar with mixed success. The flash based banners and the ads which simply get a snippet of html from the ad server work fine. However, there are some (PaddyPower I am talking about you) which return javascript and use document.write() to append the html advert to the DOM. The advert is never displayed. </p>
  
  <p>The affiliate code:</p>
  
  <pre><code>&lt;script type="text/javascript" src="someadserver.com/impression.aspx"&gt;&lt;/script&gt;
  </code></pre>
  
  <p>The script returned by someadserver.com</p>
  
  <pre><code>document.write('Normal HTML code')
  </code></pre>
  
  <p>It must have something to do with cross site scripting and security but I am no expert on this. Is there a way to achieve what I want?</p>
  
  <p>I don't believe caching is an option as it will skew the impressions/clickthrough statistics.</p>
  
  <p>Also changing any affiliate code is not an option as it is a client's website and I want a stable and workable solution that does not rely on hacking ad code.</p>
  
  <p>---EDIT---</p>
  
  <p>I modified my advert class to return the advert code surrounded by &lt;noscript&gt; tags and at the same time save the advert code in a static member. Just after my &lt;/body&gt; tag I use this code here:</p>
  
  <pre><code>    &lt;?php foreach(Advert::getCachedAds() as $id =&gt; $code): ?&gt;
      &lt;div class="advert &lt;?php echo $id ?&gt;" style="visibility:hidden;"&gt;
          &lt;?php echo $code ?&gt;
      &lt;/div&gt;
      &lt;?php endforeach; ?&gt;
      &lt;script type="text/javascript"&gt;
          $(function(){
              $('.adContainer').each(function(index, object){
                  var advert = $('div.' + $(object).attr('id')).html();
                  $('div.' + $(object).attr('id')).html('');
                  $(object).html(advert);
              });
          });
      &lt;/script&gt;
  </code></pre>
  
  <p>This works quite nicely and reminds me of the old-skool image pre-loader scripts we used to use in the days of Netscape and dial-up connections. </p>