This article may be helpful if you want to add some JavaScript code to a web page. That is needed in various situations. A good example is adding Google Analytics or other tracking scripts to the site. Also, another possible option is adding custom dynamic code that processes form events.
It should be easy to add a code to a HTML page. However, if you want to make an efficient code, there are some rules that you may need to follow. Please review the following sections to read more details about that.
Table of Contents
- What is JavaScript?
- How to add JavaScript code to the web page
- When to use the JavaScript code in a HTML web page?
- Adding JavaScript code into the head section of the HTML document
- Adding JavaScript code into the body section of the HTML document
- Using JavaScript event handlers
- Saving JavaScript code into a separate file
- The type attribute
- Performance optimization and JavaScript code minification
- Using the defer keyword
- Using the async keyword
- What is the purpose of the <noscript> element?
- Which method to use in the code
- Conclusion
What is JavaScript?
JavaScript is a scripting language that is very widely used in web development. At the beginning of its history, it was very simple. The initial goal was just to make static pages more interactive.
However, the language has evolved over time. Each version of the ECMAScript specification brings us more and more new features.
These days, you can create advanced web applications that are totally dynamic. The web pages, popup windows, navigation and forms are controlled by the JavaScript language. Even the HTML code can be generated on a fly and added to the DOM tree in a browser.
How to add JavaScript code to the web page
The JavaScript code can be added to both dynamic and static HTML pages. If you have a static website, you just have to modify the relevant .html file and add the required code.
But if you have some content management system, like WordPress or Drupal, then you may need to review the official documentation for those systems to see how the code can be added. Very likely you may need to edit the PHP files that are saved on a server. Also, there may be some plugins that allow you to dynamically add JavaScript code snippets into the site.
The most complicated situation is when you need to add JavaScript code to the web application. Usually, there may be some popular frameworks like Angular, React or Vue. In that case you would need to modify the core files. Then, the application has to be published and deployed to the web.
When to use the JavaScript code in a HTML web page?
Probably, the most popular case is adding the Google tracking code. Usually, web owners add special JavaScript code that allows them to collect analytics data, display advertisements and so on. That is a simple task and requires you only to copy a code snippet from google and insert it into the HTML document. Google does provide instructions on how to insert such a code.
However, the problem may occur when you need to make complex changes in the HTML page. For example, you may want to combine several scripts into a single block of code. Or you have to write a handler for the click event. In all such cases, you should be familiar with the basics of web development.
Adding JavaScript code into the head section of the HTML document
Each HTML web page should have a <head>
tag. That's a place where a developer can add various metadata, such as page title, styles, links, etc. And also you can add a JavaScript code there. It will be executed immediately once the page loads into the browser.
To make that, you can simply add the opening and closing tags there: <script></script>
. Inside of that block, you may put the desired code.
See the following HTML code example. It shows how to make a simple alert popup that is triggered on a page load.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>JavaScript Test</title>
<script>
alert('This is a sample application.');
</script>
</head>
<body>
<h1>This is a JavaScript test</h1>
</body>
</html>
Adding JavaScript code into the body section of the HTML document
If you want to delay execution of your inlined JavaScript code, then you may place it inside of the <body>
tag. In that case, the rendered page will appear much faster to the user.
Usually, web developers place all non-critical code in a footer of the web page. That's an important web speed optimization that is widely used in web development.
Please see the following code that shows how it can be done. You just need to move the <script></script>
code block into the desired location.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>JavaScript Test</title>
</head>
<body>
<h1>This is a JavaScript test</h1>
<script>
alert('This is a sample application.');
</script>
</body>
</html>
Using JavaScript event handlers
JavaScript code can be added to a page without the <script>
tag. The HTML specification allows you to create various event handlers that are executed by the browser.
The most popular is probably the "onclick" event. It can be used to write a code that is called when someone clicks on a button.
Please review the following sample. There, you can see how to show a simple alert window. If you run the given code and click on the "Submit" button, you'll see the "This is a sample application" message.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>JavaScript Test</title>
</head>
<body>
<h1>This is a JavaScript test</h1>
<button onclick="alert('This is a sample application.');">Submit</button>
</body>
</html>
There are many more event types available in the HTML language. For example, mouse, keyboard, focus events and others. For a full list, we recommend reviewing the official W3C specification.
Saving JavaScript code into a separate file
The inlined code has some benefits, it runs faster. However, if the code is large, you may want to add it into a separate file and save it somewhere on a server.
After that, to access it in the HTML document, you have to use the "src" attribute of the <script>
tag. There, you may specify the URL of the static JS file.
The following HTML code sample shows how to include a separate JavaScript file in a HTML document.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>JavaScript Test</title>
<script src="js/code.js"></script>
</head>
<body>
<h1>This is a JavaScript test</h1>
</body>
</html>
Loading JavaScript file inside of a body section of the HTML document
The JavaScript file may also be added into the <body>
section of the HTML document. You just have to move the <script>
tag into the desired place. No additional changes are required in the code.
It is worth mentioning that the JS files are usually large. And if you move them into the footer, the site will work much faster.
Please see the given code sample, it shows how exactly to load the JS file in the <body>
section.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>JavaScript Test</title>
</head>
<body>
<h1>This is a JavaScript test</h1>
<script src="js/code.js"></script>
</body>
</html>
JavaScript file contents
In our code sample, we use a simple JS file that only shows the alert message to the user. The source code is given below.
alert('This is a sample application.');
However, you may create a more advanced code in your web application. The JS file may contain any logic. The most important rule is that the file should have valid syntax and no compilation errors.
URL of the JavaScript file
You may provide an URL in different formats. The most common case is a relative URL. It links a file that is available on the same domain as the main application. The benefit of this method is that the page may be a little smaller in size. See our example below.
<script src="/js/code.js"></script>
Also, it's possible to use the full URL that contains the domain name and the protocol. Please see such a sample below.
<script src="https://example.com/js/code.js"></script>
The previous URL may be served from a protocol that is not currently used in a browser. For example, the web page is available on the HTTP version of the site, but the JS file is loaded via HTTPS connection.
In such a case, you can use the "//" value in your code. It should be placed before the domain name. Then, the JS file will be loaded via the same protocol that is used on the site. Our code sample is given below.
<script src="//example.com/js/code.js"></script>
The type attribute
This attribute was heavily used in the older versions of HTML. It was a requirement. You could use the "text/javascript" value there to specify that the page has a JavaScript code. Example is shown below.
<script type="text/javascript"></script>
However, in the modern versions of the HTML specification, this attribute is no longer required and should be omitted. If it's not set, then the code is treated as a regular JavaScript code and is executed by the browser.
Performance optimization and JavaScript code minification
Most web applications contain several JavaScript files. That is needed to separate the responsibility between different files. Otherwise, the single file may be too large and it would be hard for any developer to maintain and update it.
The source code of such an application would typically look like the following.
<script src="js/code.js"></script>
<script src="js/math.js"></script>
<script src="js/effects.js"></script>
<script src="js/library.js"></script>
However, such a structure creates a huge issue for use. Web pages may be very slow and users may see a delay when loading a website into a browser.
As a result, most modern content management systems and frameworks have code optimization or minification tools. If those features are enabled, the JavaScript code is saved into a single obfuscated file. The variable, function and class names are replaced with short compact names. Various formatting symbols, like spaces, new line characters are removed, and so on.
Finally, after those steps, the system produces a single JS file and adds it to the web page, like it's shown below.
<script src="js/minified_x56d5f34a7h345.js"></script>
Using the defer keyword
That's another step in page speed optimization. Usually, the JavaScript files prevent browsers from rendering the page for some short amount of time. And to avoid that, you may use the defer attribute in your code. If it's set, the JS file will be executed right after the main HTML content is parsed.
See below how to properly configure this attribute.
<script src="js/code.js" defer></script>
Using the async keyword
This attribute also allows you to execute some code that is not blocking the rendering of a page. If you use it, the script will be downloaded and parsed asynchronously while the other content is processed.
<script src="js/code.js" async></script>
What is the purpose of the <noscript>
element?
These days, the JavaScript language is available in most mobile or desktop browsers. It is very hard to find a device that can not execute a script.
However, just in case, there is a tag in HTML that allows you to display some content when the JavaScript is not enabled.
Please see the following sample. The user will see our additional message when the browser has no support of the JavaScript code.
<noscript>We are sorry, but JavaScript is not enabled in your browser.</noscript>
Which method to use in the code
Most of the frameworks or libraries already have a proper configuration. There, JavaScript files are included in the right place. It's a rare case when you need to configure how the JS files are included.
However, if you are making a custom HTML website or modifying some website theme, then you may need to manually add <script>
tags into the code.
The decision depends on what type of project you have. For simplicity, you may include several files directly in the HTML code. But for the complex project, you may use some plugins that allow you to optimize and compress JavaScript files. That is needed to improve the performance of the site.
Conclusion
As you see, it's very easy to add a JavaScript code to a HTML web page. You can do both, use the inlined code and include separate JavaScript files in the project. Each method is unique and should be used only in a specific case.
However, we do recommend reading the official W3C specification to learn more about JavaScript. There are much more interesting features in the language that you may want to use in your project.
How can I add HTML code to a template engine? Like Twig or any other?
In most cases, it should be easy to add HTML code to a template engine. You just have to follow the HTML structure of a document and use the required tags.