your codepen sample does not include the code as an external file but internally so that is an issue, but generally you need to wait for the page and all elements to finish loading.
The example bellow will wait 1000ms or 1sec and then you'll see that the alert will show the variable.
<div>
Body content
</div>
<script>
setTimeout(function() {
alert(myMessage);
},1000);
</script>
The better way is of course to use jQuery's
$('document').ready(function(){ });
instead of a timer as you can't be sure 1 second is enough. the connection might be poor and it could take more for all the pages to load.
If you dont want to use jQuery there are vanilla JS ways to do it as well.
pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it