You are here
load any external javascript file asynchronously
Sticking <script></script> tags referring an external resource in the middle of your HTML code will hang the loading of your page while your browser gets the missing script.
On the TurnKey website, this was a problem with the loading of the AddToAny sharing script, and the quantcast tag which I have since removed. There were also a couple of custom scripts that slowed down the site.
The solution is generic and simple. Use this code to load your Javascript asynchronously:
<script type="text/javascript">
(function() {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://yourdomain.com/script.js';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
})();
</script>
Instead of loading it synchronously:
<script type="text/javascript" src="http://yourdomain.com/script.js"></script>
One thing to consider is that asynchronous loaded Javascript will not block jQuery's document.ready handlers. Synchronous scripts will. If your jQuery code depends on a plugin (e.g., the simple modal dialog) it may be better to load it synchronously instead.
Add new comment