Did you know? When a Google Apps Script project containing multiple ‘files’ is run, the entire script is ‘loaded’ and run. That might include what I call Phantom Code: script content that you don’t intend to execute. This situation is more likely when you are using the recommended practice of separating your code into different gs files, each focused on a different concern.
Problems might show up as unexpected behaviours, or it might be benign but contribute to your script execution limits and slow your scripts.
To the machine, the existence of multiple gs files is moot – they are simply a convenience for the author. All functions and global variables in all files are available to code in every individual file. All statements outside the scope of functions get executed.
As a consequence, if you have something like
var sheet = SpreadsheetService.getActiveSheet(); at the top of every gs file, it will execute multiple times – so you just need such a statement once in the project.
Let’s say, like the user who asked this question, you’ve been copying and editing scripts and snippets that you’ve found on the web, and eventually find that things just aren’t working anymore. During this exercise, you’ve ended up with multiple gs files in your Google Apps Script project. How can you unravel what’s going on?
Your options at this point are:
- Make sure your data is still valid. Maybe there’s nothing wrong with the code.
- Look at the Execution Transcript after a failed run, to see if you get clues of where things went wrong. At the very least, you’ll know where it stopped.
- Review your manual merge, comparing to the original code, to ensure that you’ve copied the code properly. If you can engage a colleague as a second set of eyes for this, even better!
- Use the debugger or Logger to carefully walk through functions that you have observed misbehaving. It makes sense to start debugging with observed problems, and work backwards from there.
- Go back to the original and start over. (Renew your New Year’s resolution to begin version controlling your scripts!)
Any ideas on what might go wrong when merging scripts?
- Misplaced braces (
}) can change data structures and functions.
- Multiple copies of functions are allowed in gs, although only the bottom one will execute. You’ll get no error message in this case, but things may not act the way you expect. If, for instance, you copied functions from a companion gs file into Code.gs, then commented out the BODIES of the functions in the original file, a call to any of those functions would execute the empty version from the companion file, NOT the copy in Code.gs.
Use the editor’s search function across all files to verify that you have just ONE copy of each method, global variable, object declaration, or function.
- Operator error. We’ve all been there. Sometimes the problem is in front of the keyboard!