How to allow minimifying of public functions names in Javascript? - javascript

I don't know whether there is a solution to this issue, but I have a large set of Javascript functions bearing long descriptive names, something like:
function getTimeFromTimezoneInMilliseconds(...) { ... };
function computeDifferenceFromUTCInMilliseconds(...) { ... };
...
These long names help explaining what the code does, since some operations are complex and not obvious to understand when reading the code only. It helps maintaining the code too.
I am minimifying this Javascript code, but of course, those names are not minimified.
Is there a refactoring trick in Javascript that would allow minimifiers to pick smaller function names and reduce the code size?

You should wrap your code in an IIFE.
This way, you won't have any public members at all, and the minifier will be able to do whatever it wants.
This has the added advantage of not polluting the global scope.

Don't minify yourself! Let the machine do the hard parts.
There are many different options.
You can use an online site where you paste your code and you get the minified back (manual).
You can automate and use a server-side language to minify your JavaScript.
You can use Google CC or Yahoo YUI Compressor to minify and greatly optimize your code.

Related

How to Encode JavaScript files?

How can I encode my JavaScript file like DLL files?
I mean nobody can understand the code like Dll created from CS file in C#.
I need this because I want to give my functions to some company, but I do not want they to understand inside my functions....just can call the functions.
I see the jQuery files are encode to variables (a,b,c,d,....).
for example encode this simple code:
function CookiesEnabled() {
var result = false;
createCookie("testing", "Hello", 1);
if (readCookie("testing") != null) {
result = true;
eraseCookie("testing");
} return result;
};
There really isn't any way to encrypt/encode code like that in JS (at least I do not know of any way), but the standard way is to use good minifiers i.e. programs that collapse your code, remove comments rename local variables from good long names to stuff like width and height to stuff like a and b. And even re-structure your code so its as compact as possible. They usually end up non-human readable.
Minifing is usually even called JS compiling, but its not really. As with is a good one, well not going to go there, there are so many, but for my purposes I've been using the Microsoft official bundler:
http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification
You should also check out this question (all of the big names that I know are all there.):
Is there a good JavaScript minifier?

Big super happy javascript compression

Now, I've heard of javascript compressors, used a bunch and favour a few. However, they all do the same thing. Remove unnecessary space. That's great, they do exactly what it says on the tin. Compresses Javascript. However, looking through some of the major players that provide legendary libraries (such as jQuery), they offer "minified" sources that are entirely unreadable. Notably, the variable names change from someThingLikeThis to c. This is compression that I cannot seem to find anywhere.
My question is, where can I find a Javascript compressor which compresses variables in addition to removing unnecessary space. Or is it done manually?
For example:
// My Javascript:;
var cats = 'Nyan',
dogs = 'Hound';
alert(cats + dogs);
// jQuery styled compression:
var a='Nyan',b='Hound';alert(a+b);
As far as i know http://developer.yahoo.com/yui/compressor/ Does what you need :)
That should be done by a standard minifier. If it is not, then most likely the variable names just cannot be renamed safely (global variables/functions).
Also what you might be looking for is obfuscator. Check this question:
How can I obfuscate (protect) JavaScript?
Google Closure Compiler is the most advanced tool to transpile/minify JavaScript code.
It basically features two compilation levels—simple and advanced. You can use the simple compilation level on pretty much any JS code.
The true magic is in the advanced level which removes unused code, inlines functions, flattens properties (abc.def.ghi -> a) and renames all custom variables. But you have to write the code in a way the compiler can understand.
If you're serious about JS, read the "Closure: The Definitive Guide" by Michael Bolin who is one of the lead developers of the Closure Tools.

Any advanced tool to compress a JS file?

I'm looking for a tool to compress my JS files.
What I want is not just simply remove unneccessary characters;
I prefer to tool to be able to reduce the lengths of
local variables in functions also.
Even better I the tool can reduce the lengths of all other
stuff like global variables, function names, etc. This is to protect the code from being used by web viewers without our consent.
For example, the tool should rename a variable or function name from "some_variable", "some_function" to "sv", "sf", etc. And then refactoring all related references.
I've tried to dig the net but couldn't find something similar.
I think that this one can help you : http://www.minifyjavascript.com/
I've used it in the past and it does a good job!
The Google Closure Compiler does this. It has various settings, but even the "simple optimizations" setting will shorten variable names and (in cases where it knows the function will never be called outside the script) function names. It will even inline functions when there's a savings to be had.
For example, given this script:
jQuery(function($) {
var allDivsOnThePage = $("div"),
someParagraphsAsWell = $("p");
setColor(allDivsOnThePage, "blue");
setColor(someParagraphsAsWell, "green");
function setColor(elms, color) {
return elms.css("color", color);
}
});
Using the closure compiler with simple optimizations (and telling it we're using jQuery) yields:
jQuery(function(a){var b=a("div"),a=a("p");b.css("color","blue");a.css("color","green")});
Note how it's not only shortened the identifiers, but reused one where it detected it could (in this case that didn't save us anything, but in some other cases it could), and inlined the setColor function since that resulted in a savings.
Try YUI Compressor:
http://developer.yahoo.com/yui/compressor/
For me it seems to be one of the most powerful at the moment.

What are the arguments against the inclusion of server side scripting in JavaScript code blocks?

I've been arguing for some time against embedding server-side tags in JavaScript code, but was put on the spot today by a developer who seemed unconvinced
The code in question was a legacy ASP application, although this is largely unimportant as it could equally apply to ASP.NET or PHP (for example).
The example in question revolved around the use of a constant that they had defined in ServerSide code.
'VB
Const MY_CONST: MY_CONST = 1
If sMyVbVar = MY_CONST Then
'Do Something
End If
//JavaScript
if (sMyJsVar === "<%= MY_CONST%>"){
//DoSomething
}
My standard arguments against this are:
Script injection: The server-side tag could include code that can break the JavaScript code
Unit testing. Harder to isolate units of code for testing
Code Separation : We should keep web page technologies apart as much as possible.
The reason for doing this was so that the developer did not have to define the constant in two places. They reasoned that as it was a value that they controlled, that it wasn't subject to script injection. This reduced my justification for (1) to "We're trying to keep the standards simple, and defining exception cases would confuse people"
The unit testing and code separation arguments did not hold water either, as the page itself was a horrible amalgam of HTML, JavaScript, ASP.NET, CSS, XML....you name it, it was there. No code that was every going to be included in this page could possibly be unit tested.
So I found myself feeling like a bit of a pedant insisting that the code was changed, given the circumstances.
Are there any further arguments that might support my reasoning, or am I, in fact being a bit pedantic in this insistence?
Script injection: The server-side tag could include code that can break the JavaScript code
So write the code properly and make sure that values are correctly escaped when introduced into the JavaScript context. If your framework doesn't include a JavaScript "quoter" tool (hint: the JSON support is probably all you need), write one.
Unit testing. Harder to isolate units of code for testing
This is a good point, but if it's necessary for the server to drop things into the page for code to use, then it's necessary. I mean, there are times when this simply has to be done. A good way to do it is for the page to contain some sort of minimal block of data. Thus the server-munged JavaScript on the page really isn't "code" to be tested, it's just data. The real client code included from .js files can find the data and use it.
Thus, the page may contain:
<script>
(function(window) {
window['pageData'] = {
companyName: '<%= company.name %>',
// etc
};
})(this);
</script>
Now your nicely-encapsulated pure JavaScript code in ".js" files just has to check for window.pageData, and it's good to go.
Code Separation : We should keep web page technologies apart as much as possible.
Agreed, but it's simply a fact that sometimes server-side data needs to drive client-side behavior. To create hidden DOM nodes solely for the purpose of storing data and satisfying your rules is itself a pretty ugly practice.
Coding rules and aesthetics are Good Things. However, one should be pragmatic and take everything in perspective. It's important to remember that the context of such rules is not always a Perfect Divine Creation, and in the case of HTML, CSS, and JavaScript I think that fact is glaringly clear. In such an imperfect environment, hard-line rules can force you into unnecessary work and code that's actually harder to maintain.
edit — oh here's something else I just thought of; sort-of a compromise. A "trick" popularized (in part) by the jQuery gang with their "micro template" facility (apologies to the web genius who actually hit upon this first) is to use <script> tags that are sort-of "neutered":
<script id='pageData' type='text/plain'>
{
'companyName': '<%= company.name %>',
'accountType': '<%= user.primaryAccount.type %>',
// etc
}
</script>
Now the browser itself will not even execute that script - the "type" attribute isn't something it understands as being code, so it just ignores it. However, browsers do make the content of such scripts available, so your code can find the script by "id" value and then, via some safe JSON library or a native browser API if available, parse the notation and extract what it needs. The values still have to be properly quoted etc, but you're somewhat safer from XSS holes because it's being parsed as JSON and not as "live" full-blown JavaScript.
The reason for doing this was so that the developer did not have to define the constant in two places.
To me, this is a better argument than any argument you can make against it. It is the DRY principle. And it greatly enhances code maintainability.
Every style guide/rule taken to extreme leads to an anti-pattern. In this case your insistence of separation of technology breaks the DRY principle and can potentially make code harder to maintain. Even DRY itself if taken to extreme can lead to an anti-pattern: softcoding.
Code maintainability is a fine balance. Style guides are there to help maintain that balance. But you have to know when those very guides help and when they themselves become a problem.
Note that in the example you have given the code would not break syntax hilighting or parsing (even stackoverflow hilights it correctly) so the IDE argument would not work since the IDE can still parse that code correctly.
it simply gets unreadable. You have to take a closer look to divide the different languages. If JavaScript and the mixed-in language use the same variable names, things are getting even worse. This is especially hard for people that have to look at others people code.
Many IDEs have problems with syntax highlighting of heavily mixed documents, which can lead to the loss of Auto-Completion, proper Syntax Highlighting and so on.
It makes the code less re-usable. Think of a JavaScript function that does a common task, like echoing an array of things. If you separate the JavaScript-logic from the data it's iterating over, you can use the same function all over your application, and changes to this function have to be done only once. If the data it's iterating over is mixed with the JavaScript output loop you probably end up repeating the JavaScript code just because the mixed in language has an additional if-statement before each loop.

Tips on managing large amounts of code?

My project seems to be getting bigger and bigger and some of my classes are thousands of lines long. It's too hard to search through them every time I want to make changes.
I find JavaScript is not as easy to lay out cleanly as some other programming languages. So when the classes get to be a few thousand lines, I have troubles reading it.
I've tried splitting it into multiple files, but then you're breaking classes apart, which doesn't seem right. For example, if every method in a class uses a global variable, you would only be able to find the global variable in one of the files for that class.
Also, if I want to use the JavaScript code from 100 different .js files, I end up with something like this...
<script type="text/javascript" src="Scripts/classes/Node.js"></script>
<script type="text/javascript" src="Scripts/classes/Queue.js"></script>
<script type="text/javascript" src="Scripts/classes/DblyLinkedList.js"></script>
.... 97 more lines like this
Although, I figured there may be something where I can do...
<script type="text/javascript" src="Scripts/.../*.js"></script>
or something similar... is that right?
Anyone have any tips on managing code as it reaches its extremes?
Tips on cleaning up JavaScript code would also be helpful.
Breaking up JS into separate files has some major drawbacks, chiefly that you're forcing web browsers to make a separate request for each file.
Have you taken a look at leaving all of your files separated out, but making a single-file "bundle" for each project containing only the necessary files? This can be automated via a script.
This SitePoint article might help you get started: http://www.sitepoint.com/blogs/2007/04/10/faster-page-loads-bundle-your-css-and-javascript/
(a) keep your classes shorter [even
though that will mean yet more
files],
(b) keep them "full-text
indexed" for speed of search and
operation (not aware of any IDE
specifically supporting Javascript
this way, but strong editors like
Emacs, Vim, Eclipse, or TextMate sure
do),
(c) group them up hierarchically
so your pages can have just a few
<script> tags for "upper layer"
scripts each of which just pulls in
several of the "lower layer" ones.
Oh, and, of course, religiously keep everything under a good change control system (SVN, Mercurial, or the like), otherwise your life will be surely very very miserable:-(.
You might want to group related classes together into packages, where each package is a single file. Check out YSlow for best practices on performance.
Well, a good editor is always usefull, as it will give you shortcuts to all your functions defined in the files.
Second, make sure you're not looking at a wall of code. Indentation, spaces and newlines are a good help.
Be extremely strict in your indentation. 2 spaces is 2 spaces, always(or whatever amount you use)
if you put your { under a declaration, then always put it there, without exception)
Clear rules about how you want your text aligned will help a lot.
And I don't know about that last thing... I'm not sure browsers can work with that kind of wildcard.
<script type="text/javascript" src="Scripts/.../*.js"></script>
will not work, and besides, you end up with an interesting problem when splitting up dependent files, as you can't guarantee they will all be downloaded in the order you expected.
Unfortunately, your best bet is really a good IDE that can produce an outline for easy navigation. I use Eclipse with Spket and/or Aptana, but whatever makes it easier to manage is what you're looking for.
edit: one more quick note about splitting js into multiple files. Avoid it where possible. Each separate file means a separate http request. Reducing the number of requests required can make a massive difference in site performance.
AvatarKava's advice is sound. Work in separate files and concatenate them at build time. However, I would also recommend you take a look at your class structure. A class "thousands of lines long" doesn't sound too healthy. Are you sure you classes aren't taking on too much responsibility? Are there not tasks that can be shipped out to other single responsibility classes? This would help improve the clarity in your code far more than cunning ways of splitting files.
Same advice applies to most languages...
Avoid globals wherever possible. You can often get the desired behavior by wrapping a static variable, or using objects.
if (foo == undefined)
var foo
Use naming conventions where possible so you can track things down just by reading the variable or function names. Either that or get good with grep, or get an IDE with intellisense.
Split things into directories. Having 100 files in a directory called "classes" is not helpful. As an example, you may have a collections directory for queues, lists, trees, etc. If you've got a lot you may even have a tree subdir, or a list subdir, etc.
You can then also create a global include for that directory... simply a file called collections.js that includes all of the files in that directory. Of course you have to be careful about splitting things up well, since you don't want to be including files you'll never use.

Categories

Resources