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?
Note: Using Inline JavaScript is a bad practice and it is not recommended. It can be used for demonstration purposes so that the demonstrator doesn't have to deal with 2 separate files at a time. It is recommended to write JavaScript code in a separate .
Having inline js on different pages will make it difficult to maintain for you and others as the project scale increases. Moreover using separate js files you can encourage reusability and modular code design. keeps your html clean and you know where to look when any js error occurs instead of multiple templates.
In Raw Terms, Inline Is Faster Although the total amount of data downloaded is the same, the inline example is 30–50% faster than the external example.
When a browser encounters a script
element during the parsing of a page's HTML the following happens:
script
elements in the HTML.So, having multiple script
elements will slow down rendering of the page. The fewer script
elements present in the HTML the faster the page will render.
If your document is including scripts via the src
attrbute (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.
Insofar as there are more bytes to download, the first example is slower.
However, I'm certain that you will never be able to differentiate between the negligible micro-optimization of the latter example and the former example. Other than organization, there's no reason to bother.
That said, for the sake of organization, I would definitely bother! Keeping your code organized will speed development time. Keeping all of your JavaScript in one place will prevent you from running around searching for a snippet.
I would strive to move as much code first into an external file, and anything else into the foot of your document.
<script>
tags to the footer of the page. This will create the illusion of a faster download.Incidentally, (and just as trivially) the most optimized version of your script (aside from using an external file) would be:
<script>
var x='foo', y='bar';
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With