September 30, 2008

Loading javascript with document.write inside at the end of a page

Nikolai Kordulla

0 comments >>

For performance reasons (see YSlow for more), you should always load ad banner, which are loaded by javascript, at the end of your page. But what should you do, if the script inside the ad banner uses document.write, like Google adsense and most of all other ad networks?

Use an ad div at the end, and move it to the position, where the ad banner should be displayed. I use Google Adsense for the example.
<html>
<body>
<div id="before">Text before the ad</div>

<div id="ad_page"></div>

<div id="after">Text after the ad</div>


<div id="ad" style="display:none;">
<script type="text/javascript">
	google_ad_client = "pub-2032116925414797";
        google_ad_slot = "2428663897";
        google_ad_width = 468;
        google_ad_height = 60;
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</div>
<script type="text/javascript">
// move it to the real ad position	
document.getElementById('ad_page').appendChild(document.getElementById('ad'));
// show it
document.getElementById('ad').style.display = 'block';
</script>

</body>
</html>

Comments

 

Leave a Reply

Don't enter anything here:
Name (required) Invalid name
Mail (will not be published) (required) Invalid mail
Website Invalid url

Content couldnt be empty.