Javascript optimizations, refactor