JavaScript: the problem of blocking scripts

The concept of blocking scripts is a problem encountered by JavaScript developers when loading external dependencies on their sites. In short, JavaScript widgets or plugins can block (hence their name) the rendering of a web page when a browser takes some time to download them and execute their code. Blocking scripts are easy to recognize: when you see a web page that starts to be drawn and then you notice large chunks of empty spaces between the elements which are filled only after a couple of seconds, then it's likely that there are some scripts in the page that are slowing down the rendering of the document. I'd like to discuss some points of this topic with you.

Embedded scripts

Scripts can be embedded in a web page just like this:

<body>
	<script src="http://external.com/widgets/widget.js"></script>
	<script>
	(function() {
	
		Widget.init();
	
	})();
	</script>
</body>

When a browser encounters these two scripting blocks it must fetch the remote script first and then try to execute the JavaScript code. The problem is that if the resource is not available, the second block cannot be executed successfully.

You can code defensively and check if the corresponding library or widget is available:

(function() {

	if(typeof window.Widget !== 'undefined') {
	
		Widget.init();
	
	}

})();

There's nothing you can do on the client side when a resource is not available. In fact, each browser will raise a timeout error only after a certain amount of time, which differs from browser to browser.

Scripts in the <head> element

This kind of scripts are the worst-case scenario. Many performance experts recommend to put all your scripts just before the closing tag of the body element to avoid any unnecessary delay.

The problem is that some widgets need to be put on the top of your document to work properly. As all of you know, Twitter, Facebook, Linkedin and Google use the embedding approach (fortunately!), thus mitigating the problem.

If this is not the case, I recommend to use a local copy of the scripts, if possible. Relying on remote resources it's always risky, especially when the referring remote sites can experience significant periods of hiccups.

Consider also the possibility of using a server-side solution or a different kind of embedding, for example by using iframes.

Back to top