At the point when the script is run, the <body>
has not been reached yet and therefore document.body
is undefined (as the error you get in the console should tell you).
To fix this, simply move your script inside the <body>
- it can be right at the top if you want.
Alternatively, with basic PHP:
<body style="background-image:url(<?php
$h = date("H");
if( $h < 6) echo "http://placehold.it/450x150";
elseif( $h < 10) echo "http://placehold.it/250x150";
elseif( $h < 18) echo "http://placehold.it/350x150";
elseif( $h < 23) echo "bgbody.jpg";
else echo "http://placehold.it/450x150";
?>)">
This would avoid a "Flash of Unstyled Content" (FOUC)