JavaScript Placement

JavaScript is written in plain text, just like HTML and CSS, so you do not need any new tools to write a script. When you want to use JavaScript with a web page, you use the HTML script element to tell the browser it is coming across a script. Even though there is enough flexibility to include JavaScript anywhere in a HTML file, There are four preferred ways to include JavaScript:

Note: Don't worry about what the code means. We will focus on how the script is created and how it fits with an HTML page in different cases.

JavaScript in head.../head section of HTML
tutorial

JavaScript in body.../body section of HTML
tutorial

JavaScript in head.../head and body.../body section of HTML
tutorial

JavaScript in an external file and include it in head and/or body
A JavaScript file is just a text file (like HTML and CSS files are) but it has a .js file extension (filename.js). The HTML script element is used to load the JavaScript file into the page. It has an attribute called src, whose value is the path to the script you created. This tells the browser to find and load the script file.

HTML:
tutorial

Javascript (filename.js):
tutorial

To keep the files organized, all of your JavaScript files should be in a separate folder. It is best practice to keep JavaScript in a seprate file because more complex web development would require you to reuse identical JavaScript code on multiple pages of a site. Hence, this tutorial will follow the same convention.

NEXT LESSON