Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do many websites put all of their JavaScript on a single line?

Tags:

javascript

I'm starting to learn JavaScript for my first language and I am kind of starting to get the hang of it.

But I'm beginning to check out source codes of .js files in websites and I see a lot of people put the the entire script in just one line which. For one, this is hard for me to understand from a learning point, but my main question is: is there a benefit for doing this, rather than coding it in more of a block style?

like image 395
T Mik Avatar asked Jul 14 '11 15:07

T Mik


3 Answers

The developers of the code won't be writing it like that themselves, they'll be using a normal style. Because JavaScript isn't compiled, developers often run it through a tool called a minifier instead:

Minification in computer programming languages and especially JavaScript, is the process of removing all unnecessary characters from source code, without changing its functionality. [...] Minified source code is especially useful for interpreted languages deployed and transmitted on the Internet (such as JavaScript), because it reduces the amount of data that needs to be transferred.

Minified code is harder to understand; this is often seen as a feature because it makes it harder for other people to copy your code and use it themselves. Some minification tools, such as Google's Closure Compiler, also optimize the code, improving performance and removing redundant code.

You should develop using normal indented code and, if you want, run it through a minifier when publishing it on your web server.

like image 106
Jeremy Avatar answered Nov 10 '22 13:11

Jeremy


benefit for doing this rather

It makes the script smaller, so it downloads faster.

than coding it in more of a block style

The scripts will be coded in block style. They are just minified as part of the publishing process.

like image 24
Quentin Avatar answered Nov 10 '22 13:11

Quentin


For file size. The easiest way to reduce the number of bytes downloaded to a user's browser is to remove all unnecessary whitespace (including newlines) from every JavaScript and CSS file. Depending on the number of lines, that could save several kilobytes.

like image 33
Ry- Avatar answered Nov 10 '22 12:11

Ry-