PDA

View Full Version : Reducing JavaScript size


landon11
12-17-2002, 09:38 PM
what are some tips to decrease the size of my files.

krycek
12-17-2002, 09:44 PM
delete them :D

::] krycek [::

Skyzyx
12-17-2002, 09:52 PM
Use shorthand as much as possible. For example:

Instead of this...
foo=foo+1;

Use this...
foo++;

or

Instead of
foo=foo+'bar';

Use
foo+='bar';


Instead of:
if (true statement)
{
document.write('Do this');
}
else
{
document.write('Do this other thing');
}

Use this:
if (true statement) document.write('Do this');
else document.write('Do this other thing');


Hope this helps.

landon11
12-17-2002, 09:58 PM
Yes, thank you, this is the kind of things I was wanting to know.

instead of:

if (true statement) x=1;
else x=2;


would this be much help?

x=(true statement)?1:2;

Skyzyx
12-17-2002, 10:00 PM
Yes, that would work. Actually, I use that syntax alot when I'm browser sniffing...

beetle
12-17-2002, 10:53 PM
Yes, ternary statements are great for variable assignment. You can 'nest' them also. Let's consider and example from another post (http://www.codingforums.com/showthread.php?s=&threadid=11654). Although the switch statement I posted is the best (IMHO) algorithm for that problem, let's see if we can do it with a ternary, shall we?x = x.toUpperCase();
points += (x == 'A') ? 4 : (x == 'B') ? 3 : (x == 'C') ? 2 : (x == 'D') ? 1 : 0;Harder to read and modify, but compact!

Skyzyx
12-17-2002, 10:54 PM
Beautiful, Beetle!

Vladdy
12-18-2002, 12:07 AM
See the script I posted: http://www.codingforums.com/showthread.php?s=&threadid=10070
It removes all the comments and extra spaces which, depending on your coding practice can be 20% - 50% of the script size.

krycek
12-18-2002, 12:56 AM
Originally posted by Vladdy
See the script I posted: http://www.codingforums.com/showthread.php?s=&threadid=10070
It removes all the comments and extra spaces which, depending on your coding practice can be 20% - 50% of the script size.

hehehe a JS obfuscator :D

...if anyone wants one in Perl or PHP, give me a shout :)

::] krycek [::

whammy
12-18-2002, 01:36 AM
I love ternary operators. :)

They make VB users look bad, for one thing... hehe...

I'm going to use as many as possible with ASP.NET in my c# code to tick them off. ;)

landon11
12-18-2002, 03:21 PM
Thank you all.
Vladdy,
I tried your script and it did reduce the size of the file by 1/2 but
the functions don't work anymore. Any ideas?

Vladdy
12-18-2002, 07:50 PM
Once you get rid of all the new lines, you need to make sure that you have semicolons in all the places. If you think that the error is caused by the script - send me the original file and I will look at it.

landon11
12-18-2002, 08:06 PM
That is going to be my problem, I need to add semicolons.
Thanks.

beetle
12-18-2002, 08:14 PM
I wish javascript would require semicolons. It's mandatory to end code statments in EVERY other C-based scripting language. But, because it doesn't, some people don't then get all wigged out when they start coding PHP, Perl, or C/C++/C#.

jkd
12-18-2002, 08:16 PM
Readability is much more important than language "features" in the long run.

Remember that next time you are thinking about "compacting" code, and how much pain it'll cause to edit it.

You're not getting any discernable performance benefit by saving bytes of code, and a few bytes here and there really don't make a difference in the world of cable and dsl modems, nor even 56k modems.

Just thought I'd add an opposing view to this thread.

krycek
12-18-2002, 08:31 PM
Well I agree with both of you :D (just to add a third view lol)

Obfuscation can be very useful... first of all you don't always want a script to be published with all your notes and comments in it :)

Also seeing as the file size can often be cut in half, it IS useful bandwidth-wise, whether you look at it from the point of the user (quicker loading) or the server (less consumed bandwidth per visitor).

Some of us don't care about those things, but some of us do - and to those that do, an obfuscator can be very useful!

If you belong to those people that do like obfuscation, then this link may be useful (taken from my bookmarks heheh):

JS Cruncher (http://www.domapi.com/jscruncher.cfm)

joh6nn is correct about readability but you should never obfuscate/compact a script you are going to edit - only do it to a copy that you are going to publish (and don't lose the original! :D)

one thing about semi-colons: if you like to use them, a cruncher can help you make sure that they are all there. If you don't like to use them, don't use crunchers. There is no middle ground :p

Oh yeah and I am on 2Mbit ADSL btw, so I am not bothered about my own download speeds ;)

::] krycek [::

landon11
12-18-2002, 08:54 PM
Yes, I have many back ups but I was wondering if you could run a script to "undue" the compacting. And I am still having syntax problems. I write my code such as:


function myFunction(){
var myVal = 1;
var myVal2 = 2;
if(myVal > myVal2){
alert(myVal + "is greater than " + myVal2);}
else{
alert(myVal2 + "is greater than " + myVal);}}

ca_redwards
12-27-2002, 09:45 PM
In my HTML() bookmarklet library (http://www.angelfire.com/ca/redwards/html__.calendar.html), I define 154 functions (with less than 2K!) that allow me to dramatically reduce the size of the JavaScript needed to build common HTML constructs.

In the examples on the linked documentation page, there is a calendar, a websafe color palette, and a web page editor. Each is less than 2K!

See you in the5k.org contest next year!

RadarBob
12-28-2002, 05:10 AM
Interesting discussion. The problem is that almost all of you are presuming a problem but none of you (us) presents any imperical evidence that suggest there is a problem in the first place...

I agree with jkd.

I have no idea how big a "typical" HTML page is but I'd bet that given the total size (including any scripts) minus some miniscule savings by removing comments, obsfucating code, and deleting carrage returns makes no more that a couple of seconds difference on loading.

I agree with the suggestions that readable, understandable, editable, extinsible, etc. code is MUCH more important.

beetle
12-28-2002, 06:17 AM
For those of you that are interested, I've taken the algorithms in the brainjar JS cruncher and ported them to PHP (well, some of it). It's not done, but here's the code, and a link to it (http://www.peterbailey.net/js_server2.php?file=/fValidate/js/fValidate) serving up my fValidate script. fValidate is 27.8kb. This PHP-served version is 9.2kb and is fully functional. Like everyone has said, this maybe saves a second or less, but takes the server almost no time at all (haven't timed it yet) and allows you to send a crunched version to the browser without maintaining it manually :D It was a fun little exercise anyhow ;)<?php
//*************************************************
// PHP Javascript Server
// Peter Bailey - 2002
//
// This JS server strips JS files of all unecessary
// comments, spaces, and newlines
//
// Code based on algorithms in Mike Hall's
// JS Cruncher found at www.brainjar.com
//*************************************************

$literalStrings; // For temporary storage of literal strings

$file = $_GET['file'];
$ext = ".js";
$filename = $_SERVER['DOCUMENT_ROOT'] . $file . $ext;
$fp = fopen( $filename, "r" );
$f = fread( $fp, filesize( $filename ) );

#$f = replaceLiteralStrings( $f );
$f = stripAll( $f );
#$f = restoreLiteralStrings( $f );

print( $f );

function stripAll( $s )
{
$ps = array( "/([^\\/]*)\\/\\/.*$/m", // Remove '//' comments from each line.
"/\n/m", // Replace newline characters with spaces.
"/\\/\\*.*\\*\\//U", // Remove '/* ... */' comments.
"/(\})/m", // Add in semicolons after brackets
"/\\s+/", // Reduce multiple space blocks
"/^\\s(.*)/", // Remove leading spaces
"/(.*)\\s$/", // Remove Trailing spaces
"/\\s([\\x21\\x25\\x26\\x28\\x29\\x2a\\x2b\\x2c\\x2d\\x2f\\x3a\\x3b\\x3c\\x3d\\x3e\\x3f\\x5b\\x5d\\x5c\\x7b \\x7c\\x7d\\x7e])/",
"/([\\x21\\x25\\x26\\x28\\x29\\x2a\\x2b\\x2c\\x2d\\x2f\\x3a\\x3b\\x3c\\x3d\\x3e\\x3f\\x5b\\x5d\\x5c\\x7b \\x7c\\x7d\\x7e])\\s/",
"/\"\+\"/", // Combine string literals
"/'\+'/" // Combine string literals
);
$rs = array( "\\\\1",
" ",
"",
"\\\\1\n",
" ",
"\\\\1",
"\\\\1",
"\\\\1",
"\\\\1",
"",
""
);

return preg_replace( $ps, $rs, $s );
}
?>

krycek
12-28-2002, 12:51 PM
That's pretty good, beetle :)

As to radarbob and co, I think you are missing the point of this.

Yes having JS that is readable, understandable etc. is important, but ONLY to the developer. The user will probably never read it, and the percentage of those who do is small... with the percentage who try to use the code, even smaller.

Some of my JS file benefit hugely from compaction/crunching. I like to use a lot of tabs in my code; this makes it very readable to me. I also use a lot of comments. I recently compacted a 22Kb JS file down to only 7Kb. That's nearly 70% taken off.

When you think in terms of bandwidth, which is often the most important thing about sites, a saving like that multiplied by many visitors can be important. It does not take long to do - even if it is done every time with a script like beetle's (which is more inefficient than a once-off conversion but also saves the trouble of having more than one copy of the file).

Personally I think any points like keeping the script readable (which I deem unimportant in publication) are outweighed by benefits in speed and bandwidth usage, even if small :)

::] krycek [::

Vladdy
12-28-2002, 03:54 PM
beetle,

I would remove the block comments first.
Consider the following block comment:

/* Here is first line of the block comment
on the last line // I decide to have two forward slashes */

If I read your code right (I'm just geting into php) it will first strip the // and everything after it to the end of line with very undesirable consequences ;)

krycek
12-28-2002, 03:59 PM
Very true, vladdy.

Also I am not sure why semi-colons are being added after brackets? :confused: They are not needed... plus there seems to be nothing to check if they are inside a string sequence.

::] krycek [::

beetle
12-28-2002, 04:27 PM
Sheesh, I though I covered myself in this area!Originally posted by beetle
It's not done...Scrutinize it when I say it's finished! :D

Oh, and krycek, if you notice, I actually don't add semicolons, I add a newline. This was becuase some scripts I've tested would break without it. I guess I need to update that comment :D

Vladdy, thx for the tip.

krycek
12-28-2002, 05:06 PM
heheh fair enough :) I didn't look at much of the code, just skimmed through :)

::] krycek [::

landon11
07-11-2003, 07:25 PM
Vladdy,
I have been using your script for a while now with no problems but we recently went to 2003 Server with IIS 6.0 and it no longer works.

bettle,
Did you ever finish the cruncher you were working on?

Vladdy
07-11-2003, 07:28 PM
If you send me a CD with Server 2003 , IIS 6.0 and activation code, I will gladly find out what is wrong ;) .

beetle
07-11-2003, 10:00 PM
Unfortunately, no. I've been swamped with the next release of fValidate.