
JavaScript
JavaScript Placement
The JavaScript code can be placed anywhere in an HTML document. However, most developers prefer placing it in the following sections:
- Script in <head>
- Script in <body>
- Script in an external file
The <script> Tag
In an HTML file, the JavaScript code is placed between <script> and </script> tags.
JavaScript in <head> and <body>
JavaScript code can be placed in both the <head> and <body> elements.
JavaScript in <head>
JavaScript code can be inserted in the HTML page’s <head> section. The codes add functionality to the file. After placing the function in the head section, click the button to call the function.
JavaScript in <body>
Like <head>, the <body> section of the HTML file can be used to place a JavaScript function. Click the button to call the function.
Pro Tip: When using script tags, you may need to compromise on page speed, as they can slow down the display. Adding the script tags at the bottom of the <body> section will improve the page’s display speed.
JavaScript in External File
When using the same JavaScript code, it is hectic to insert the same code on multiple HTML pages. A practical solution to this is storing JavaScript code in an external file and then inserting it into your desired web pages or HTML files.
JavaScript in External File Benefits
Placing JavaScript codes in external files offers several benefits. Such as:
- It keeps the HTML and JavaScript codes separate.
- It improves readability and makes both HTML and JS easier to maintain.
- You can enhance page loading speed by caching JavaScript files.
External References
The external JavaScript files can be added to the HTML files in three ways.
With a Full URL
When using an external JavaScript file that is not a part of the same project, it should be added by using the full URL. For example
With the Relative File Path
When JavaScript and HTML files of a project are in different folders, then you can use the relative file path method to insert the code.
project-folder/
│── index.html
│── scripts/
└── myScript.js
With the Filename Only
If both the HTML and JavaScript files of your project are in the same folder, then this method is preferred. With this, you can add the script without following any path.
project-folder/
│── index.html
│── myScript.js