How do you add JavaScript to your page?
JavaScript is applied to your HTML page in a similar manner to CSS. Whereas CSS uses <link> elements to apply external stylesheets and <style> elements to apply internal stylesheets to HTML, JavaScript only needs one friend in the world of HTML — the <script> element. Let’s learn how this works.
Internal JavaScript
JavaScript can be added directly to the HTML file by writing the code inside the <script> tag. We can place the <script> tag either inside <head> or the <body> tag according to the need.
Advantages of using Internal JS:
- The browser does not have to make an extra HTTP request for JavaScript code.
- It does not allow caching.
Disadvantages of Internal JS:
- The readability of code becomes poor.
- Maintenance of code becomes hard when there is a lot of code.
External JavaScript
The other way is to write JavaScript code in another file having a .js extension and then link the file inside the <head> or <body> tag of the HTML file in which we want to add this code.
Advantages of using External JS:
- HTML and JavaScript files become more readable and easy to maintain.
- Page loads speed up due to Cached JavaScript files.
Disadvantages of External JS:
- Coders can easily download your code using the url of the script(.js) file.
- An extra HTTP request is made by the browser to get this JavaScript code.