title: window.onload event doesn't fires or "how to properly initialize js project?"
body: <p>This problem seems to be common, though I couldn't find the answer.</p>
  
  <p>I've got this simple html with the only canvas tag</p>
  
  <pre><code>&lt;!doctype html&gt;
  
    &lt;head&gt;
      &lt;meta charset = "utf-8"&gt;
      &lt;script src="js/script.js"&gt;&lt;/script&gt;
      &lt;title&gt;Title&lt;/title&gt;
    &lt;/head&gt;
  
    &lt;body&gt;
      &lt;canvas id = "canvas"&gt;&lt;/canvas&gt;  
    &lt;/body&gt;
  
  &lt;/html&gt;
  </code></pre>
  
  <p>and in script.js I'm trying to catch window.onload event:</p>
  
  <pre><code>window.onload = init;
  
  function init(){
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
  
    context.fillRect(50, 20, 150, 150);
  }
  </code></pre>
  
  <p>But nothing happens. I assume that the html is loaded even before the first line of js executed.</p>
  
  <p>So I found that the alternative to onload event would be to put script definition in the end of the body, so when script being executed the window is supposed to be loaded alreade. So I did like this:</p>
  
  <pre><code>&lt;!doctype html&gt;
  
    &lt;head&gt;
      &lt;meta charset = "utf-8"&gt;   
                                    &lt;!-- gone --&gt;
      &lt;title&gt;Title&lt;/title&gt;
    &lt;/head&gt;
  
    &lt;body&gt;
      &lt;canvas id = "canvas"&gt;&lt;/canvas&gt; 
      &lt;script src="js/script.js"&gt;&lt;/script&gt;  &lt;!-- inserted --&gt;
    &lt;/body&gt;
  
  &lt;/html&gt;
  </code></pre>
  
  <p>and</p>
  
  <pre><code>&lt;!-- window.onload = init; --&gt;
  init()                              &lt;!-- inserted --&gt;
  
  function init(){
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
  
    context.fillRect(50, 20, 150, 150);
  }
  </code></pre>
  
  <p>And in a way it works (draws rectangle) <strike>, but gives me an error <strong>Uncaught ReferenceError: context is not defined</strong>. </strike></p>
  
  <p>So my question is what I'm doing wrong? I'm also wonderring if there is a better way to do this.</p>
  
  <p>P.S. I tend not to use jquery...</p>
  
  <p><strong>EDITED:</strong> the error with context has nothing to do with the code above, although I still don't like the idea of putting the link to js file in the end of the body...</p>