Development
Comments Off How To: Delay JavaScript Source Load
I recently ran into a problem with a 3rd party JavaScript source call slowing down the load of one of my sites. I decided to change the code to perform a document.write of the external source tag when the page’s initialize JS code ran. Apparently the 3rd party developers wrote code to test for the correct insertion of their code, and whenever I made this change the script suddenly stops working, and instead pops up a JS alert saying that you need to place the code between the “<body></body>” tags. Their validation code is erroneous, but that doesn’t help me. I ended up finding a solution to my problem in the following script I found online. Somehow adding the code dynamically do the head tag doesn’t trigger the same warning, and the script still works.
var head= document.getElementsByTagName(‘head’)[0];
var script= document.createElement(‘script’);
script.type= ‘text/javascript’;
script.src= ‘http://www.example.com/script.js’;
head.appendChild(script);