Here is a sneak peek at how integrating the language into HTML code can change the look and feel of the page.
- JS components allow webpages to work offline. This way, web browsers can keep up with desktop software and be fully functional even when there’s no Internet access.
There are two ways to integrate JS into a static HTML page:
- Creating an external file for JS editing and refer to it in the HTML code.
Let’s take a look at how to handle both, examine their respective benefits and drawbacks.
Editing the HTML file
Adding JS directly to the HTML file is nor a common way of integration – however, this one is easier for beginners to master. Also, if you want to add a lot of page-specific code, pasting it directly into the page document is more convenient than creating a separate document.
Here’s a step-by-step tutorial on how to edit your HTML document to add JS to the website:
Use <script> and </script> tags at the beginning and the end of JS code blocks.
Here’s how the script added to the <head> of the page looks like:
<title> Here's my HTML page </title> <script> MyScriptName.js </script> </head>
If you want to add the code to the body of the page, the code will look like this:
<head> <title> Here's my HTML page </title> </head> <body> <script> MySciptName.js </script> </body> </html>
Adding a script to an HTML page takes seconds – yet, it’s enough to improve the interactivity of the code by huge numbers.
Note: Most developers don’t use direct HTML editing to embed robust scripts or those that run on multiple pages because pasting dozens of code lines into the backbone document of the page complicates maintenance and reduces code readability. If you want to implement JS into your website on a large scale, consider choosing a different approach.
If you pay attention to the structure of most HTML pages, you will find out most of them reference multiple HTML files rather than pasting them one by one directly. This approach yields developers the following benefits:
- Higher code readability and compactness;
- Improved maintenance and more room for scalability;
- Referencing a file rather than pasting it directly improves the performance of a page.
To reference .js code in HTML, you can either:
- Create a JS directory to reference the code as an external asset (similar to CSS stylesheets). In this case, the code will look the following way:
project/ |- css/ I I- stylesheet_name.css |- js/ | |- script_name.js |- index.html
- Insert <script src=’script.name.js’></script> within <body></body>, where the attribute in the opening tag refers to the source of the JS file.
- Validating users’ emails and login data;
- Displaying dynamic content – dates and such;
- Adding auto-filling to forms and word suggestion to search tabs;
- Updating website data in real-time without reloading the page;
- On-page animation;
- Ensuring the uniformity of the interface across different browser clients.