jQuery append Google Adsense to div

You can't include external scripts that way.

To include javascript after the page has loaded, you should use jQuery's jQuery.getScript() function, but I don't know if that would work for Google Adsense.

A little more info can be found here:

http://geek.littleredstring.com/17-load-adsense-last-jquery


The way I do this is by having a placeholder on the spot I want the ad to appear.

<html>
   <body>
      <div id="googleadgoeshere"></div>
   </body>
</html>

Then place the google-code in a container at the end of the page.

<div id="adsense" style="display:none;">all the google javascript goes here</div>

I then use jQuery to move the iframe the adsense code creates once the page is done loading.

$(window).load(function(){
    $("#adsense").find("iframe").appendTo("#googleadgoeshere"); 
    $("#adsense").remove();
});

If you just try to move the #adsense div you will end up with a blank page. If you try to do this most any other way, you will end up with a blank page. Google had built in active ways to check that the code is not moved. If it is, your page will be blank. Why google has done this is beyond me, but I have found this workaround to work for me...


Add a hidden DIV with adsense code in your page somewhere:

<div id='adsense' style="display:none">
    <script type="text/javascript"><!--
        google_ad_client = "ca-pub-xxxxxxxxxxxxxx";
        google_ad_slot = "xxxxxxxxxx";
        google_ad_width = 300;
        google_ad_height = 250;
        //-->
    </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</div>

Using javascript create dynamic DIV for your ad to load:

$("body").append("<div id='adslot' ></div>");

Jquery code to insert the Ad:

var ad = $("#adsense").html();
$("#adslot").html(ad);

This works for me.


After trying and failing with the codes on here, I ended up taking the jQuery object that I was using and putting it in a new html page. Once I did that, I just used an iframe to place it on the page with the adsense.

Now, adsense and jQuery run at the same time with no problems.