0

I have some javascript that runs fine after being compiled through Closure with SIMPLE_OPTIMIZATIONS. But I would like to perform ADVANCED_OPTIMIZATIONS which performs dead code removal.

After reading some relevant documentation here, I believe my main() function, which I call through <body onload="main()"> is being eliminated by my compiler. To confirm this, I put a console.log('hello'); line of code in my main() function. When opening up the results of Closure compilation with simple and advanced optimizations in a text editor, I can find that console.log('hello'); in the simple version, but it is not present in the advanced version.

So my question is, is there an elegant way to tell the compiler that main() is not unreachable? (Or perhaps am I doing something else wrong..)

newprogrammer
  • 2,514
  • 2
  • 28
  • 46

2 Answers2

3

Bind it with an event listener instead of inlining it in your html. For example instead of:

HTML

<body onload="main()">Test</body>

JS

var main = function() { /* Do something */ }

Use

New JS

var main = function() {
    console.log("Here!");
}
window.addEventListener("load", main);

Then you can remove onload="main()" from your HTML. This is also considered good practice in JavaScript.

soktinpk
  • 3,778
  • 2
  • 22
  • 33
0

You can also use the --closure_entry_point flag. Whatever file has main in it, put something like goog.provide('myapp.entrypoint') in that file, and then pass --closure_entry_point=myapp.entrypoint to the compiler.

Tyler
  • 21,762
  • 11
  • 61
  • 90