How can I insert Adsense Code with jQuery's insertAfter()?

I’m trying to insert an Adsense block after .myclass on my website but so far no success…
Does anyone know how I can make this work?
Any help would be much appreciated…

This is what I’ve tried so far, but it’s not working:

  <script type="text/javascript"><!--
  google_ad_client = "ca-pub-xxx";
  google_ad_slot = "xxx";
  google_ad_width = xxx;
  google_ad_height = xxx;
  <script type="text/javascript" src=""></script>

Hi there,

The bad news is that inserting a dynamically created <script> tag using jQuery and .append() isn’t going to work.

The reason for this is as follows:

All of jQuery’s insertion methods use a domManip function internally to clean/process elements before and after they are inserted into the DOM. One of the things the domManip function does is pull out any script elements about to be inserted and run them through an “evalScript routine” rather than inject them with the rest of the DOM fragment. It inserts the scripts separately, evaluates them, and then removes them from the DOM.


The good news is that you can do it in plain old JavaScript, like so:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Unbenanntes Dokument</title>
    <div id="myDiv">Hello</div>
      var inlineScript   = document.createElement("script");
      inlineScript.type  = "text/javascript";
      inlineScript.text  = '<!--google_ad_client = "ca-pub-xxx"; google_ad_slot = "xxx"; google_ad_width = xxx; google_ad_height = xxx;//-->' 
      var externalScript   = document.createElement("script");
      externalScript.type  = "text/javascript";
      externalScript.src = "";

No matter where in the web page you try to insert your Google ads using that code the ad will always be added immediately after the script that runs the code because that’s how the document.write statements in the Google script work. Even though the script tag gets added as a child of the MyDiv div, the ad itself will be added after the </script> tag already in the page because everything up to that point in the page has already been created before the document.write runs to insert the ad.

With the code as shown in Pullo’s example the ad will be shown where expected because there is nothing between where the ad is supposed to go and where it actually does go. If there is anything else between the </div> and <script> tags then that content will appear above the ad when you would expect that it ought to appear below the ad.

Consider this:

<div id="myDiv">Hello<!-- script tag is actually inserted here  but ad doesn't appear here --></div>
    <p>An added paragraph of text so you can see the difference.</p>
      var inlineScript   = document.createElement("script");
      inlineScript.type  = "text/javascript";
      inlineScript.text  = '<!--google_ad_client = "ca-pub-xxx"; google_ad_slot = "xxx"; google_ad_width = xxx; google_ad_height = xxx;//-->' 
      var externalScript   = document.createElement("script");
      externalScript.type  = "text/javascript";
      externalScript.src = "";
<!-- ad actually appears here -->

To rectify this you need something that is going to parse the Google script code itself and replace the document.write statements. I still haven’t found one that will work without requiring that you create your own updated copy of to replace the document.write statements - which would mean the ads would break each time Google change that script. I am still looking for something that will rewrite that script to replace the document.write statements dynamically in between loading the script and running it.

Thanks for those detailed explanations :), so it seems like this will be a difficult thing to achieve…

There is a website though ( that seems to have already achieved this, that’s how I originally got this idea.
Here’s an example page on their website that show’s the ad being inserted after the 2nd paragraph:

My javascript is not good enough to decipher that code though, but on that page I can see that the Google ad is inserted at “<div class=“stepAd”>”.

Do not even attempt to work out how to use the JavaScript on that page - it is extremely antiquated, the scripts are jumbled throughout the page and it has document.write statements all over the place - obviously aimed at Netscape 4 or an earlier browser.

You can place Google ads anywhere in the web page as long as you put the script that initiates the display of the ad in the spot in the page where you want the ad to appear so that when the antiquated Google script uses document.write to output the ad immediately after the </script> tag that it ends up displaying where you want.

What unfortunately can’t be done is to keep all of the JavaScript in a separate file attached to the web page by one script tag immediately before the </body> tag as should be done for modern JavaScript - any prehistoric document.write statements would then output their content at the very end of the page. The modern innerHTML and DOM calls would output their content where ever in the page you tell them to even with a single external script attached to the bottom - one of many reasons to not use document.write - unfortunately Google have never employed any JavaScript programmers and so all of their scripts are at best prehistoric in their approach if not completely broken.

But that would defeat the purpose right? I mean if I can only put the script that initiates the display of the ad where the ad should be anyway, I might as well put the Adsense code there directly. To elaborate, here’s my situation and what I’m trying to do exactly:

I’m using the ExpressionEngine CMS system, with I output articles with the {article} variable, to my knowledge I can’t modify the contents of this variable to do what I like to do (insert an ad after the first paragraph) unless I place the ad code directly in every single article that I write (very unpractical). So that’s why I was trying to do this with jQuery or now plain javascript, but understanding from your words… If I cannot put the ad inserting script in the spot where the ad is supposed to go this can never work? I mean, I can’t put the ad inserting script in that spot because that spot is inside an ExpressionEngine template variable that I don’t have direct access to.

I’m not familiar with the intimate workings of the ExpressionEngine CMS system but approaching the problem as a purely server side-scripting & database issue then either a PHP string replace tacked onto the text input script or in the template and do the swap on-the fly, or you could use an SQL search+replace statement to achieve what you want.

When writing the article just add a short marker text/phrase where you want the advertisement to appear for example: <place_adsense_1> and the str_replace function can insert all the advert code required before it gets sent to the database for storage. With a little work the marker text could be dispensed with if the script can identify where the second paragraph ends… Alternatively SQL could be used as part of a stand-alone script separate from the CMS code that can be called at anytime to seek out the marker text and perform the insertion of new code into the database.

UPDATE some_CMS_table SET article_column  = REPLACE("article_column" ," <place_adsense_1>","adsense code...."  )

I have just found a way to attach the AdSense JavaScript to the bottom of the web page (where all the JavaScript belongs) and have it insert the ad in the right place. I had been looking for a solution to this for several years whenever someone reminded me about the stupid problem with Gooogle’s code (still written with Netscape 3 in mind because of the document.write statements).

Step One - Go to and get the postscribe.js and htmlparser.js files.

Step Two. Create a separate ad99.js file for each ad with the ad code in it and using postscribe to add the external script from Google.

google_ad_client = "pub-9999999999999999";
google_ad_slot = "9999999999";
google_ad_width = 300;
google_ad_height = 250;
postscribe('#adv1','<script type="text/javascript" src=""><\\/script>');

Step Three. Add a div with the specified id (id=“adv1” in my example) where you want the ad to appear.

Step Four. Repeat steps two and three for any additional ads - each needs to be in a separate file as the postscribe call must be the last line.

Step Five. Add the following to the bottom of your page immediately before the </body> tag - listing each of the ad scripts you created in place of ad1.js and ad2.js (update the src to include the path to where ever you put the scripts).

<script type="text/javascript" src="postscribe.js"></script>
<script type="text/javascript" src="htmlparser.js"></script>
<script type="text/javascript" src="ad1.js"></script>
<script type="text/javascript" src="ad2.js"></script>

I believe that the htmlparser script originated with John Resig who also created JQuery. I came across a version of that code with his name on it a couple of years ago but was never able to figure out how to get it to place Google ads in the right place (I could get the script tags for the ad inserted at the right spot but the ad still appeared after the script that added those tags rather than in that spot. Those responsible for postscribe appear to have resolved that problem so that the ad itself will also appear where it is supposed to.

Serving ads after the page has loaded seems like problem for most common ad engines. We use APT and have been investing ways to do this for a while. The best method we have come up with to buffer the ads in an external iframe than move them into the parent window. You could also serve each ad in an iframe if you don’t need to worry about syncing multiple ads on a page when using something like a campaign. As a matter of fact this is the method used on the below page to dynamically change ads without reloading the page.

The ad engine is Yahoo APT but I believe the concept would be similar. Pretty much each time a new add needs to be served jQuery.html() is used to ad an iframe which references a page that only serves a single ad. The necessary ad engine parameters are passed to the html page as a query string and parsed using JavaScript on that page. Far from ideal but given the limitations of the ad engine implementation it seems to be the best method I have discovered to date.

I’m going to have investigate that postscript method though because using iframes is far from ideal.

I found an ExpressionEngine Specific Solution! :slight_smile: It’s exactly what I need, made for exactly that purpose (injecting ads) and more…

This is the plugin I’m talking about: