JavaScript refactoring

(Also fixes #186)