I suggest you to move this view to header.php where all other scripts/styles are placed so we can have them in one file. You can use $( document ).ready(); and move your code inside ready(), in order to ensure that DOM will be loaded before the script gets executed.