title: How to run JavaScript code as soon <body> element is defined?
body: <p>Here is my code:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Foo&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
  
    &lt;script&gt;
      console.log('test')
    &lt;/script&gt;
  
    &lt;p&gt;
      Foo
    &lt;/p&gt;
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>I want to move the JavaScript in this code from <code>&lt;body&gt;</code> into <code>&lt;head&gt;</code>. Here is my incorrect attempt:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Foo&lt;/title&gt;
    &lt;script&gt;
    window.onload = function () {
      console.log('test')
    }
    &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  
    &lt;p&gt;
      Foo
    &lt;/p&gt;
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>This of course does not do what I want. It runs the JavaScript only after the whole page has loaded. But I want the JavaScript to run as soon as <code>&lt;body&gt;</code> is defined. Can this be done in JavaScript?</p>