Adrian Adkison
Adrian Adkison

Reputation: 3757

scripting adds with document.write vs. jQuery append

I have taken time to review many of the discussions on this topic but have not found an answer to my question.

In my site I am trying to optimize my page load speed and one of the ways I would like to do that is to move the my ad scripts to the bottom of the page to allow my content to load first. I still want the ad to show up in the middle of the page.

the ad code currently is in a script block in the middle of the page and looks something like this

<div id="topAd">
  <script>

  document.write('<s' + 'cript lang' + 'uage="jav' + 'ascript" src="' + src + '"></' + 'scr' + 'ipt>');
  </script>
</div>

what I would like to do is something like this at the bottom of the page

<script>
  var script = document.createElement('script');
  script.src = src;
  jQuery('#topAd').append(script);
</script>

Unfortunately this always loads the content at the bottom of the page and not inside the "topAd" div. Can anyone explain why this is happening?

Upvotes: 1

Views: 10395

Answers (3)

cess
cess

Reputation: 11

your script must be:

<script type="text/javascript">
var topad = $('#topAd');
    $('#yourRequiredDiv').append( topad );
</script>

Upvotes: 1

Oscar Kilhed
Oscar Kilhed

Reputation: 1816

Try using iFrames.

  1. Make a page on your own domain that serves the ad script tag.
  2. Replace the ad divs with iframes.
  3. Add a script tag at the bottom that replaces the location of the iframes so that the iframe serves the page created in step one.

    document.getElementById('iframeId').contentWindow.location.replace('your-page-that-serves-the-ad-script');
    

Upvotes: -2

meouw
meouw

Reputation: 42140

Your ad script is using document.write to generate it's content so it'll appear after any content that is already on the page when it is invoked.
You could put the original content at the bottom and then move it perhaps?

<div id="yourRequiredDiv"></div>

<!-- more content -->

<div id="topAd">
  <script>

  document.write('<s' + 'cript lang' + 'uage="jav' + 'ascript" src="' + src + '"></' + 'scr' + 'ipt>');
  </script>
</div>

<script type="text/javascript">
    $('#yourRequiredDiv').append( $('#topAd') );
</script>
</body>

Would that work?

Upvotes: 2

Related Questions