开发者

javascript - how to minfy/obfuscate global function names?

I have some code that has the following format:

function myfunc1 () { ... jquery.bind('click', myfunc2) ... }
function myfunc2 () { ... }
...

Yes, the functions are global, but it's ok since I'm writing within a google chrome extension content script, so it's sandboxed.

Now, I'm trying to minify and obfuscate the code. I've tried YUI Compressor and the Google Closure compiler. The problem is, I can't figure out how to minify/obfuscate the global function names. With YUI it doesn't minify the global variables in case they're called externally. With Closure in advanced mode, it seems like it can rename the global variables, however I'm having problem with the dead code rem开发者_如何学Coval. Most functions appear to be dead since they depend on DOM interaction and event handling and aren't called directly.

So any idea on how to minify these global variables? Do I need to just write a script to do some regex replacement? I'm also open to refactoring my code if that would fit the minification pattern better (for example, adding to a closure or whatnot)


Minifiers won't munge public/global names since, for many scripts, that will destroy the availability and predictability of the public API.

Since you don't need to maintain a public API, making them "private" by wrapping them in a closure function may be enough:

(function () {

    function myfunc1 () { ... jquery.bind('click', myfunc2) ... }
    function myfunc2 () { ... 
    ...

})();

But, even then, no guarantees as it's very much at the discretion of the minifier's authors.


See the Semantic Designs JavaScript Obfuscator. Gives you complete control over what symbols are obfuscated, and which are not, precisely so you can manage situations like this. No need to change your working code.

I work for them.


Please see the on-line docs for the Closure Compiler.

In other words:

  1. "Export" the functions you want to keep
  2. Make an "externs" file with functions you don't want renamed
  3. Run Closure Compiler in Advanced Mode


You could make local references to commonly used jQuery functions in your code, which would then be minified?

For example:

$(function() {
   var jQueryAnimate = $.animate,
       jQueryAddClass = $.addClass;

   $('.foo').jQueryAddClass('.bar');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜