JavaScript Scratches

Where To Put Your JavaScript

Developing for a web environment can be a bit of a bear if you're writing your own code. All my code is hand-rolled, so one of the first things I needed to know is where to put the code for my scripts.

Similar to using Cascading Style Sheets (CSS), the code can be placed in different locations.

It can be placed anywhere in your HTML code wrapped in <script>...</script> tags.

Once again

It can be placed anywhere in your HTML code wrapped in <script>...</script> tags.
And you can have as many blocks of JS code as you like, sprinkled throughout your HTML.
However: It will be executed where you place it.

This is handy for a one-off and simple bit of code. A typical and sensible place is the <head> section.

A better place (best practice) is to place all JavaScript code in a separate text file. A sensible extension is usually .js but could be something else (.txt).

This separates your JavaScript code from the HTML code of the site, so easier to find and manage.

The JavaScript code for this page is in the file myJS.txt, in the <head> section.

<script src="myJS.txt"></script>

Use the 'View Source' feature of your browser to see how.

Datatypes & Variables