As you suggested it might be better to write this code as external js file.