Why do we have newlines in minified JavaScript?

后端 未结 3 1341
伪装坚强ぢ
伪装坚强ぢ 2020-12-06 00:30

I know about a similar question but it is a tiny bit off from what I am asking here, so please don\'t flag it as a duplicate.

When you

相关标签:
3条回答
  • 2020-12-06 00:46

    To cite the Closure Compiler FAQ:

    The Closure Compiler intentionally adds line breaks every 500 characters or so. Firewalls and proxies sometimes corrupt or ignore large JavaScript files with very long lines. Adding line breaks every 500 characters prevents this problem. Removing the line breaks has no effect on a script's semantics. The impact on code size is small, and the Compiler optimizes line break placement so that the code size penalty is even smaller when files are gzipped.

    This is relevant to any minification programs in general.

    0 讨论(0)
  • 2020-12-06 00:52

    The lines (excluding the license) are all around 30k characters in length. It could be to avoid bugs where some Javascript parsers die on extremely long lines. This probably won't happen on today's browsers but maybe some older or more obscure ones have such limits.


    (Old answer below, which might also be applicable, just not in this case)

    This might be because JSMin, a popular Javascript minifier will retain line feeds in the output under certain conditions. This is because in Javascript line feeds are significant if you leave out semicolons, for example. The documentation says:

    It is more conservative in omitting linefeeds, because linefeeds are sometimes treated as semicolons. A linefeed is not omitted if it precedes a non-ASCII character or an ASCII letter or digit or one of these characters:

    \ $ _ { [ ( + -
    

    and if it follows a non-ASCII character or an ASCII letter or digit or one of these characters:

    \ $ _ } ] ) + - " '
    

    Other minifiers might have similar rules.

    So this is mostly a precaution against accidentally removing a line feed that may be necessary, syntax-wise. The last thing you want is that your minified JS won't work anymore because the minifier destroyed its semantics.

    Regarding »I know three newlines (not counting the license) is not going to slow it down a lot, but still, doesn't every tiny bit help?«: When your server uses gzip compression the difference will likely be moot anyway.

    0 讨论(0)
  • 2020-12-06 00:55

    jQuery currently use UglifyJS to minify their source code. In their build script, they specifically set the max_line_length directive to be 32 * 1024:

    The documentation for UglifyJS has this to say on the max-line-len directive;

    --max-line-len (default 32K characters) — add a newline after around 32K characters. I’ve seen both FF and Chrome croak when all the code was on a single line of around 670K. Pass –max-line-len 0 to disable this safety feature.

    0 讨论(0)
提交回复
热议问题