I’m trying to optimize the loading time of a site that has a lot of JS spaghetti code. Some of it actually looks like this:
<script>var x="foo";</script>
<script>var y="bar";</script>
Instead of the sane-programmer code:
<script>
var x="foo";
var y="bar";
</script>
So I was wondering whether this kind of thing actually does harm? Aside from the aesthetics, would combining the scripts into a single script tag bring any loading time benefit?
When a browser encounters a
scriptelement during the parsing of a page’s HTML the following happens:scriptelements in the HTML.So, having multiple
scriptelements will slow down rendering of the page. The fewerscriptelements present in the HTML the faster the page will render.If your document is including scripts via the
srcattrbute (e.g.<script src="http://example.com/myscript.js">) then you can use the async attribute to delay script processing. This is a feature supported in newer browsers (e.g. Firefox 3.6 and Webkit based browsers released since September 2010). But inlined scripts will still block parsing until they have been interpreted.