JavaScript: Overcome Slow Loading JavaScript On A Web Page

Sometime a web page may load slowly due to loading a third party JavaScript source file from other domain. Most of the time, a web site comes with advertisement scripts or scripts for keep tracking visitors and these scripts are normally provided by third parties like Google Adsense, Statcounter, Amazon and etc. When these scripts’ loading speed is extremely slow, it blocks the whole page from loading.

One of the way to overcome the slow loading of JavaScript problems is to move the code that load the JavaScript file to the end of the website before the body tag. For example, . This is so that the browser can load and render the whole page and then only load and run the script.

But this does not actually solve most of the problem. This is because in most time, in most JavaScript, the programmers will use the document.write() method to render the HTML code at the position where the JavaScript is loaded. For example, if you move the source line that load aadvertisement to the bottom of the page and left the parameters on top, the advertisement will be loaded at the bottom of the page.

To solve this problem, we can implement a simple tricks with little JavaScript code. The idea is like this:

  • Put a empty div place holder at the place where you originally want to put and give it a unique name, let’s say ads1_ori.
  • Put a hidden div place holder at the bottom, put the scripts that load slowly inside the place hold and give it a unique name, let’s say ads1_new.
  • At bottom of the page, right before the body tag, write a few line of JavaScript code to load the HTML content from ads1_ori to ads1_new.

Example of implementation:

<html>
  <head><title>Some Web Site</title></head>
  </body>

  ....

  <div id="ads1_ori "></div>

  ...

  <div id="ads1_new" style="display:none">
    <!-- advertisement -->
    <script type="text/javascript">
      paramenter = "abcdefg";
    </script>
    <script type="text/javascript" src="http://www.example.com/some_script.js"></script>
    <!-- advertisement -->
  </div>

  <script type="text/javascript">
    document.getElementById('ads1_ori').innerHTML = document.getElementById('ads1_new').innerHTML;
  </script>
  </body>
</html>
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • NewsVine
  • Reddit
  • StumbleUpon
  • Google Bookmarks
  • Yahoo! Buzz
  • Twitter
  • Technorati
  • Live
  • LinkedIn
  • MySpace
  • Mixx

Related posts:

hit 166 views This entry was posted on 29 Nov,11:20 am,2009 and is filed under
How to?, Javascript, Webmaster Resources You can leave a response, or trackback from your own site.

Filed Under: How to?JavascriptWebmaster Resources

Tags:

RSSComments (0)

Trackback URL

Leave a Reply




If you want a picture to show with your comment, go get a Gravatar.

Security Code: