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, <script type='text/javascript' src='http://www.example.com/some_script.js'></script>
. 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 a advertisement 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 sayads1_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 sayads1_new
. - At bottom of the page, right before the
body
tag, write a few line of JavaScript code to load the HTML content fromads1_ori
toads1_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>
jez says
while the concept sounds amazing it does not work for me. I tried this idea with google adsense and the ad would just not show up at all. any idea? thanks
szehau says
Hi jez,
I have no problem using the code for Google Adsense. Maybe you have some coding error in your JavaScript?