Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to rename document variable in javascript

I noticed that Google Closure Compiler did not rename document to something like d to reduce space.

I cannot think of a case where this would break the code (ie where document points to something else down the road). Actually the same goes for window.

Is there a reason for protecting document this way?

== EDIT ==

By renaming it I was thinking reassigning it. Example below.

var d=document;
var obj1=d.getElementById("obj1");
var obj2=d.getElementById("obj2");
... // with enough uses of document so it makes to reassign it size-wise.
like image 686
Mad Echet Avatar asked Aug 27 '13 07:08

Mad Echet


2 Answers

Closure-compiler does not perform this "optimization" by default for the simple reason that it produces LARGER source when used with gzip. You can enable this optimization by turning on the AliasExternals pass using either the Java API or a custom build.

See https://code.google.com/p/closure-compiler/source/browse/src/com/google/javascript/jscomp/AliasExternals.java#38

like image 54
Chad Killingsworth Avatar answered Oct 09 '22 23:10

Chad Killingsworth


What happens?

ProblemFactory's guess is correct.

This is a //TODO in the closure compiler source code. If we didn't preserve document and window and instead ran them over with d for example, at the moment the closure compiler does not know if it's overriding a global from another file. Like the comments say this will be resolved in the future at which point.

Enough words, show me the source!

If we check the closure compiler source code inside VariableReferenceCheck.java we can find the following:

 private class ReferenceCheckingBehavior implements Behavior {

    @Override
    public void afterExitScope(NodeTraversal t, ReferenceMap referenceMap) {
      // TODO(bashir) In hot-swap version this means that for global scope we
      // only go through all global variables accessed in the modified file not
      // all global variables. This should be fixed.

      // Check all vars after finishing a scope
      for (Iterator<Var> it = t.getScope().getVars(); it.hasNext();) {
        Var v = it.next();
        checkVar(v, referenceMap.getReferences(v).references);
      }
    }

If we check the hot-swap algorithm itself we can see that:

// Note we use the global scope to prevent wrong "undefined-var errors" on
// variables that are defined in other JS files.

So, we can see that this is just the closure compiler not understanding the code of globals across multiple files well enough to make that replacement. You can always do the replacement yourself :)

like image 23
Benjamin Gruenbaum Avatar answered Oct 09 '22 23:10

Benjamin Gruenbaum