Skip to content Skip to sidebar Skip to footer

Add Javascript Into A Html Page With Jquery

I want to add a javascript google ad but I can't insert the javascript into the div using jquery. I try to simulate my problem with this test, which is using some advice I found on

Solution 1:

See my answer to Are dynamically inserted <script> tags meant to work? for why you can't use innerHTML, which jQuery's functions map to when passed a HTML string, to insert a script element. document.write will also fail when used after the document has been fully parsed.

To work around this, you will have to use DOM functions to insert an element into the div. Google ads are iframes, so it's usually a case of finding the iframe code and appending that instead.


To correctly insert a script element, you need to use DOM functions, for instance:
var txt = 'alert("Hello");';
var scr = document.createElement("script");
scr.type= "text/javascript";

// We have to use .text for IE, .textContent for standards compliance.if ("textContent"in scr)
    scr.textContent = txt;
else
    scr.text = txt;

// Finally, insert the script element into the divdocument.getElementById("insert_here").appendChild(scr);

Solution 2:

I figured out a great solution:

  1. Insert your Google Adsense code anywhere on your page - e.g. if your CMS only allows you to put this on the right hand side then stick it there.
  2. Wrap a div around it with display:none style
  3. Add some jquery code to move the div to the location you desire.

Since the javascript has already run there is no problem then with moving the block of script to wherever you'd like it to be.

e.g. if you wish to put 2 blocks of google adverts interspersed throughout your blog (say after paragraph 1 and after paragraph 4) then this is perfect.

Here's some example code:

<divid="advert1"style="display:none"><divclass="advertbox advertfont"><divstyle="float:right;"><scripttype="text/javascript"><!--
        google_ad_client = "pub-xxxxxxxxxxxxxxxxx";
        /* Video box */
        google_ad_slot = "xxxxxxxxxxxxxxxxx"
        google_ad_width = 300;
        google_ad_height = 250;
        //--></script><scripttype="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script></div></div></div><script>
$(document).ready(function() {

$('#advert1').appendTo("#content p:eq(1)");
$('#advert1').css("display", "block");

});
</script>

p.s. #content happens to be where the content starts on my CMS (Squarespace) so you can replace that with whatever you have in your CMS. This works a treat and doesn't break Google ToS.

Solution 3:

You cannot use document.write after the page has finished loading. Instead, simply insert the contents that you want to be written in.

<scripttype="text/javascript">
     $(function() { // This is equivalent to document.readyvar str="hello world";
         $('#insert_here').append(str);
     });
</script>

Post a Comment for "Add Javascript Into A Html Page With Jquery"