JS refactoring and performance improvements