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?
Related
Using RequireJS, I've build a small script. Depending on what is passed to a function, another file gets required – so it's something like a real simple factory probably. Imagine it like this:
function MyThing(a) {
if (a > 2) {
this.script = require['lib1'];
} else {
this.script = require['lib2'];
}
}
I other languages (I am coming from PHP), I can implement the same interface in both classes and be sure that lib1 and lib2 both share the functions defined in the interface.
If it worked like that in JavaScript, down the road I could call this.script.getId() or something like that and it would just work, no matter if lib1 or lib2 would be used.
Unfortunately, there are no interfaces in JavaScript (this Answer explained very well why it wouldn't make sense), so I am a bit stuck on how I should deal with it.
Of course I could create something like an interface that maps to both libs, but I have the feeling this would be the wrong way to deal with it.
What is the right approach towards the problem I am encountering?
You can just use duck typing, which exploits the fact that JS can convert anything and everything into a boolean value. If a function exists, its coerced boolean is true, so:
var lib = doMagicLoading();
// does the lib support the function we need?
if (lib.functionINeed) {
// it does, so we can simply move on along our intended code path.
lib.functionINeed();
} else {
// if it does not, that might be a problem, or it might not be. Warn us:
console.warn("library does not implement the function I Need...");
}
This is also how JavaScript code makes sure it does "the right thing" on different browsers that support different versions of JS, for instance. Step 1: test whether the function exists. Step 2: call it if does, or do something else if it doesn't.
Of course, in your case, as the programmer responsible for having working code you can actually guarantee well behaved code, because of course you wrote tests for your scripts, to make sure both code paths do the right thing, and you bundled your code using r.js before deploying. If not: it's time to start writing tests. Don't just trust developers to write working code -- that includes yourself =)
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.
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.
Calling the javascript gurus out there.
Basically my question is regarding how you structure your code, both visually and for functionality for example do you wrap everything in objects using this structure:
var myapp={
binds:function(){
//put some event listeners for jquery etc...
},
otherfunc:function(){
//do some other thing
},
init:function(){
//call myapp.binds and other functions and other stuff to intialize your app.
}
};
Then finally
$(document).ready(myapp.init);
The thing is with a structure like this I think JSLint complains doesn't it? Whats the pros and cons using a structure like this or is there a generally better way to structure your code? Do you follow a certain pattern from $(document).ready(call) to putting all your event listeners and "initializing" your app, do you use separate objects for methods and variables?
I also think "visually" if you have a very large webapp this structure eventually looks very messy, but maybe it's just me I don't know, any input is appreciated thanks.
Using Inheritance Patterns to Organize Large jQuery Applications
explain in detail and with better practice by Alex
http://alexsexton.com/?p=51
its very very well explain, must see
other links
How To Manage Large jQuery Apps 5 months ago
It doesn't matter much how you structure your code as long as you follow the essentials rules of programming that your teacher thought you:
Don't write repetitive code
A function must do 1 and only 1 thing
Document your code
Some other small things but mostly the above... oh and apply lots of common sense
The only error you get from that is "implied global." You can get rid of the warning for document by using this.document instead (since window is the context). The implied global for $ will stay unless you paste in the jQuery source (then gl with all the errors in that).
I trust JSLint--a lot. On big projects I tend to make object literals as you did above but I use a module pattern for object security:
var myapp = (function () {
var secret_stuff, public_stuff;
return {
stuff: public_stuff
}
}());
We have lots of javascript functions, which are usually handled via the onclick function. Currently they are present in every file where-ever it is needed. Would it make sense to consolidate all javascript functions into a single file and use this where-ever it is needed? What is the general practice here
<s:link view="/User.xhtml"
onclick="if (confirm('#{messages['label.user.warning']}')) {
var f = $('user');
f.method = 'POST';
f.action = f.submit();
} return false;">
Yes! Absolutely factor this out into an external javascript. Imagine if you needed to change something in this code. How many places do you have to change now? Don't duplicate code. It must makes your page bigger, which obviously affects how much is getting downloaded.
It's up to you to determine where the reusability lies in your own code. But it's easy enough (and a good idea) to create a library of often-used functions. Create a file like mylib.js, for instance, with things like...
function saveUser(f)
{
//...
f.method = 'POST';
f.action = f.submit();
}
add this to your pages:
<script type="text/javascript" src="mylib.js"></script>
add code your events like this:
<s:link view="/User.xhtml" onclick="return saveUser($('user'));">
Notice that the library code avoids any dependencies on the layout or naming of elements on the pages that use it. You may also want to leave little comments that will remind your future self what the purpose and assumptions of these library functions are.
Would it make sense to consolidate all javascript functions into a single file and use this where-ever it is needed?
Ummm...yeah
It would be better to do something like this:
function saveUser() {
// logic goes here
}
and use the markup
<s:link view="..." onclick="saveUser();">
Using code inline like that is very bad. Don't do it. Or the prorgamming gods will grow restless.
It is always a good idea to put JavaScript code in JavaScript files. Like you don't mix content and presentation (XHTML and CSS), you don't have to mix content and interactivity (XHTML and JavaScript).
Putting JavaScript code in a separate file has several advantages:
No need to duplicate code (so better reuse),
Possibility to minify the source code, thing which is quite impossible to do if you put together XHTML and JavaScript,
Ability to use non-intrusive JavaScript, helping to create more accessible websites (there is probably nothing wrong from the accessibility point to use onclick and other events, but it becomes very easy to forget that the website must work without JavaScript, thus developing a non-accessible website).
Better client-side performance: larger pages make things slower; when you put JavaScript outside, the pages are smaller, and the .js file is cached by the browser instead of being loaded on every request.
Javascript can be accessed via a script tag, which can point to an external script or define it for use in this document only.
<script type="text/javascript" src="mycustom.js"></script>
<!-- OR -->
<script type="text/javascript">
function saveUser(username) {
//code
}
</script>
No offense, but if you didn't know that you are either very new at this or you skipped a lot of steps in learning javascript. I recommend going through the w3schools.com tutorial on javascript and anything else you'll be using.