In this blog post, we’ll discuss how to integrate JavaScript code into a web page created using HTML.
Per tradition (like almost every book on programming languages), we will start with a very simple Hello World example, which only produces the output Hello World. This is not very exciting yet, but right now the point is to show you how to embed a JavaScript file in an HTML file in the first place and how to execute the source code contained in the JavaScript file.
Preparing a Suitable Folder Structure
For getting started and working through the following examples, we recommend that you use the directory structure shown in the figure below for every example. The HTML file is at the top level because this is the entry point for the browser and thus the file you will invoke in the browser right away.
However, it is a good idea to create different folders for the CSS and JavaScript files. The names styles (for CSS files) and scripts (for JavaScript files) are quite common. Especially if you are dealing with a lot of different JavaScript and CSS files during development, this separation (or an arrangement with subfolders in general) makes it easier to keep track of your project.
Most of the examples in this post also follow the layout shown in the figure above as we will only run the JavaScript code in the browser at the beginning, using the index.html file as a kind of entry point to the program.
While you can execute JavaScript within a browser without creating an HTML file to embed the corresponding script (via special developer tools provided by browsers), for now we don’t want to use this feature.
Creating a JavaScript File
As mentioned earlier, it’s better to save JavaScript code in a separate file (or in several separate files) that can then be embedded in the HTML code. So the first thing you need is a JavaScript file. Simply open the editor of your choice (or if you didn't take my advice, the development environment of your choice), create a new file, enter the lines of source code provided in the listing below, and then save the file under the name main.js.
function showMessage() {
alert('Hello World');
}
JavaScript files have the extension .js. Other file extensions are also possible, but the .js extension has the advantage that editors, development environments, and browsers directly know what the content is about. You should therefore always save all JavaScript files with the .js extension. (By the way, browsers recognize JavaScript files delivered by a web server via the Content-Type header, a piece of information that comes with the file from the server.)
The previous code listing defines a function with the name showMessage, which in turn calls another function (with the name alert) and passes it the message Hello World. The alert function is a JavaScript standard function.
Embedding a JavaScript File in an HTML File
To use the JavaScript source code within a web page, you need to link the JavaScript file to the web page or embed the JavaScript file in the HTML file. This is done via the HTML element named <script>.
This element can be used in two different ways: On the one hand, as we will demonstrate subsequently, external JavaScript files can be included in the HTML. On the other hand, JavaScript source code can be written directly between the opening <script> tag and the closing </script> tag.
An example of the latter method will be shown later, but this approach is only useful in exceptional cases because JavaScript code and HTML code are then mixed—that is, stored in one file (which is not a best practice for the reasons already mentioned). So let's first look at how to do it properly and include a separate file.
The <script> element has a total of six attributes, out of which the src attribute is certainly the most important one: it’s used to specify the path to the JavaScript file that is to be included. This table shows an overview of what the other attributes do.
Now create an HTML file named index.html and insert the content shown below:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Example</title>
<link rel="stylesheet" href="styles/main.css" type="text/css">
</head>
<body>
<!--Here the JavaScript file will be included -->
<script src="scripts/main.js"></script>
</body>
</html>
If you now open this HTML file in the browser, nothing will happen yet because the function we defined earlier is not yet called at any point. Therefore, add the showMessage() call at the end of the JavaScript file, as shown in the code below, and reload the web page in the appropriate browser. Then a small hint dialog should open, containing the message Hello World and with a slightly different appearance depending on the browser.
function showMessage() {
alert('Hello World');
}
showMessage();
Multipurpose Internet Mail Extension (MIME) types, also called internet media types or content types, were originally intended to distinguish between content types within emails containing different content (such as images, PDF files, etc.). Now, however, MIME types are not only used in the context of email, but also whenever data is transmitted over the internet. If a server sends a file with a special MIME type, the client (e.g., the browser) knows directly what type of data is being transmitted.
For JavaScript, the MIME type wasn’t standardized for a long time, so there were several MIME types—for example, application/javascript, application/ecmascript, text/javascript and text/ecmascript. Since 2006, however, there is an official standard (www.rfc-editor.org/rfc/rfc4329.txt) that defines the acceptable MIME types for JavaScript. According to this standard, text/javascript and text/ecmascript are both deprecated, and application/javascript and application/ecmascript should be used instead. Ironically, it’s safest not to specify any MIME type for JavaScript at all (in the <script> element) as the type attribute is ignored by most browsers anyway.
Of course, you can embed several JavaScript files within one HTML file. Simply use a separate <script> element for each file you want to include.
Defining JavaScript Directly within the HTML
For the sake of completeness, we’ll also show how you can define JavaScript directly within an HTML file. While this is usually not advisable because it means mixing HTML and JavaScript code in one file, it won’t hurt to know that it still works.
Simply write the relevant JavaScript code inside the <script> element instead of linking it via the src attribute. The listing below shows the same example as in the previous section, but it doesn’t use a separate JavaScript file for the JavaScript code. Instead, it embeds the code directly in the HTML. The src attribute is therefore omitted completely. <!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Example</title>
<link rel="stylesheet" href="styles/main.css" type="text/css">
</head>
<body>
<script>
function showMessage() {
alert('Hello World');
}
showMessage();
</script>
</body>
</html>
Note that <script> elements that use the src attribute must not contain any source code between <script> and </script>. If there is any, this source code will be ignored.
Use separate JavaScript files for your source code instead of writing it directly into a <script> element. This creates a clean separation between the structure (HTML) and the behavior (JavaScript) of a web page.
You can use the <noscript> element to define an HTML section that is displayed when JavaScript is not supported in the browser or has been disabled by the user (see listing below). However, if JavaScript is supported or enabled, the content of the <noscript> element will not be shown.
<noscript>
JavaScript is not available or is disabled. <br />
Please use a browser that supports JavaScript,
or enable JavaScript in your browser.
</noscript>
Placement and Execution of the <script> Elements
If you had asked a web developer a few (many) years ago where to place a <script> element within a web page, they probably would have advised placing it in the <head> area of the web page. In the early days of web development, people thought that linked files such as CSS files and JavaScript files should be placed in a central location within the HTML code.
Since then, however, this idea has been abandoned. While CSS files are still placed in the <head> area, JavaScript files should be included before the closing </body> tag instead. The reason is this: when the browser loads a web page, it loads not only the HTML code but also embedded files such as images, CSS files, and JavaScript files. Depending on processor performance and memory usage, modern browsers are capable of downloading several such files in parallel. However, when the browser encounters a <script> element, it immediately starts processing the corresponding source code and evaluating it using the JavaScript interpreter. To be able to do this, the corresponding JavaScript source code must first be downloaded entirely. While this is happening, the browser pauses downloading all other files and parsing (i.e., processing) the HTML code, which in turn leads to the user impression that it takes longer to build the web page.
In addition, you will often want to access HTML elements on a web page within the JavaScript source code. If the JavaScript code is executed before these HTML elements have been processed, you’ll encounter an access error.
If you place the <script> element before the closing </body> tag, though, you are on the safe side in this regard, because in that case all elements included inside the <body> element are already loaded (with the exception of other <script> elements, of course).
As a rule, you should position <script> elements at the end of the <body> element. This is because the browser first evaluates the JavaScript source code contained or embedded in each <script> element before continuing to load other HTML elements.
Two attributes that can be used to influence the loading behavior of JavaScript are the async and defer attributes, which we already mentioned briefly. The former ensures that the processing of HTML code is not paused when the browser encounters a <script> element. The JavaScript file is downloaded asynchronously (hence the name async). This concept is shown in this figure.
As you can see, the JavaScript code is executed right away as soon as the corresponding JavaScript file has been completely downloaded.
The defer attribute takes this one step further. On the one hand, just like async, this attribute ensures that the HTML code processing is not paused. On the other hand, the JavaScript source code is executed only after the HTML code has been fully processed (see next figure). The execution of the JavaScript code is effectively deferred (hence the name defer).
So when should you use which attribute? For now, you can bear in mind that it’s probably best not to use either attribute by default. The async attribute is only suitable for scripts that work completely independently and have nothing to do with the HTML on the web page. An example of this is the use of Google Analytics. The defer attribute, on the other hand, is currently not supported by all browsers, so you should also consider its use with caution.
Another way to ensure that all the content of the web page has been loaded before JavaScript code is executed is to use event handlers and event listeners.
In general, both event handlers and event listeners are used to respond to certain events that occur during the execution of a program and to execute certain code. (There is a small, subtle difference between event handlers and event listeners, but it's not important for now.) Events can be mouse clicks, keystrokes, window resizing actions, and more. For web pages, too, there are various events that are triggered and can be answered by such event handlers and event listeners. For example, an event is triggered when the content of a web page is fully loaded.
To define an event handler for this event, you can use the onload attribute: The code you specify here as the value for such an attribute is invoked when the web page is fully loaded. As a value, you can specify a JavaScript statement, such as the call to a function, as shown in this listing.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Example</title>
<link rel="stylesheet" href="styles/main.css" type="text/css">
</head>
<body onload="showMessage()">
<script src="scripts/main.js"></script>
</body>
</html>
Event listeners, however, cannot be defined via HTML. Instead, you use the addEvent- Listener() function of the document object (more on this later), to which you pass the name of the event and the function to be executed when the event is triggered, as shown in this code:
function showMessage() {
alert('Hello World');
}
document.addEventListener('DOMContentLoaded', showMessage);
The showMessage() call you just added to the end of the main.js file will need to be removed again in both cases. Otherwise, the function will be called twice (once by the script itself and once by the event handler/event listener), and as a consequence a message dialog will be displayed twice in succession.
Displaying the Source Code
All browsers usually provide a way to view the source code of a web page. This can be helpful in many cases—for example, if you want to check how a particular feature is implemented on a website you have discovered.
In Chrome, you can view the source code by following menu path View > Developer > View Source.
In Firefox, it’s Tools > Browser Tools • Page Source.
For Safari, it’s Develop > Show Page Source.
In Opera, it’s Developer > View Source.
And in Microsoft Edge, it’s Tools > Developer > View Source.
If you look at the source code of more complex web pages, it’s often very confusing. This is usually due to multiple reasons: on the one hand, content is often generated dynamically, and on the other, JavaScript is often deliberately compressed and obscured by web developers—the former to save space, the latter to protect the source code from prying eyes.
If you display the source code of a web page (no matter in which browser), you are first presented with the corresponding HTML code of the web page. Conveniently, however, embedded files such as CSS files or JavaScript files are linked in this source code view (first figure below) so that you can easily get to the source code of the linked file as well (second figure).
Editor’s note: This post has been adapted from a section of the JavaScript: The Comprehensive Guide by Philip Ackermann. Philip is CTO of Cedalo GmbH and author of several reference books and technical articles on Java, JavaScript and web development. His focus is on the design and development of Node.js projects in the areas of Industry 4.0 and Internet of Things.
This post was originally published 4/2025.
Comments