async your scripts!

I’m not that much of a JavaScript ninja, though I’m trying to get there. The new hotness in the field definitely seems to be loading everything asynchronously, which allows the page to load first, and the JS to sprinkle in afterwards to litter the page with whatever special sauce. In my case, I’m running this site on WordPress, and most sites now have JavaScript loaders for the various “share this link” buttons. I came up with this solution which is now working quite well for me, so I wanted to share:

	var s = document.getElementsByTagName('script')[0];

	var asyncScripts = new Array(

	for (var i = 0; i < asyncScripts.length; i++) {
		var l = document.createElement('script');
		l.type = 'text/javascript'; l.async = true;
		l.src = asyncScripts[i]; s.parentNode.insertBefore(l, s);

Rather than include the <script> tags at every instance, place this at the bottom of your HTML, and edit the array asyncScripts to match the JS files you want to load. Everything is wrapped in an anonymous function, which just goes through each item in that array and loads the corresponding script. As a result, the share buttons don’t block loading the rest of the page, and each required resource is only loaded once rather than N times for each N button on the page.

Leave a Reply