Where Does JavaScript Go and Why?
Because we will create the programming logic for the Canvas in JavaScript, a question arises: where does that JavaScript go in the pages we have already created?
It’s a good idea to place your JavaScript in the <head>
of your HTML page because it
makes it easy to find. However, placing JavaScript there means that the
entire HTML page needs to load before your JavaScript can work with the
HTML. This also means that the JavaScript code will start to execute
before the entire page loads. As a result, you will need to test to see
whether the HTML page has loaded before you run your JavaScript
program.
There has been a recent move to put JavaScript right before the
</body>
at the end of an HTML
document to make sure that the whole page loads before the JavaScript
runs. However, because we are going to test to see whether the page has
loaded in JavaScript before we run our <canvas>
program, we will put our
JavaScript in the traditional <head>
location. If you are not
comfortable with this, you can adapt the style of the code to your
liking.
No matter where you put the code, you can place it inline in the HTML page or load an external .js file. The code for loading an external JavaScript file might look like this:
<
script
type
=
"text/javascript"
src
=
"canvasapp.js"
><
/script>
To make things simple, we will code our JavaScript inline in the HTML page. However, if you know what you are doing, saving an external file and loading it will work just as well.
Note
In HTML5, ...
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.