That's happens because the script run before document is ready. ( sync ).
If you want to keep your script at the beginning of the body, or in head, use de window.onload function.
window.onload = function()
{
// your code goes here
}
My suggestion will be to place the
scriptat the end of the body, also thebootstrapandjquerylibs, because those scripts will be fired after the DOM is ready.