Amazon Ad Banner not loading properly inside hidden or dynamically loaded content

When using an Amazon Affiliate Ad Banner inside content that’s hidden during page load for whatever reason (such as accordions), you’ll find that it doesn’t work. It simply won’t display.

The easiest workaround/solution I was able to find is Postscribe.

Basically, you’ll want to insert the script tag

<script src="//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US"></script>

dynamically into the content when it’s made visible (for example, when the accordion is opened). However, that is not enough. The Amazon ad script uses document.write() to insert its html into the content. But since you’re effectively loading the script after the document has already been parsed and closed, document.write() won’t work – you’ll get this error:

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

The solution is to use Postscribe, which hijacks document.write() in a safe way and does some black magic to make it work.

A quick solution for Bootstrap accordion:

$('.accordion-content').on('shown.bs.collapse', function() {
  postscribe('#ad-container', '<script src="//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US"><\/script>');
});

 

Indrek Kõnnussaar

I'm a veteran Wordpress developer, context-driven tester, security enthusiast and the mastermind behind Codelight. I love building stuff that works and fixing stuff that doesn't.

Write me directly indrek@codelight.eu
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×