JavaScript Where To
In HTML, JavaScript code is inserted between <script> and </script> tags.
Example
Old JavaScript examples may use a type attribute: <script type="text/javascript">.
The type attribute is not required. JavaScript is the default scripting language in HTML.
JavaScript Functions and Events
A JavaScript function is a block of JavaScript code, that can be executed when "called" for.
For example, a function can be called when an event occurs, like when the user clicks a button.
You will learn much more about functions and events in later chapters.
JavaScript in <head> or <body>
You can place any number of scripts in an HTML document.
Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML page.
The function is invoked (called) when a button is clicked:
Example
<h2>Demo JavaScript in Head</h2>
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML page.
The function is invoked (called) when a button is clicked:
Example
<h2>Demo JavaScript in Body</h2>
<script>
function myFunction() <
document.getElementById("demo").innerHTML = "Paragraph changed.";
>
</script>
Placing scripts at the bottom of the <body> element improves the display speed, because script interpretation slows down the display.
External JavaScript
Scripts can also be placed in external files:
External file: myScript.js
External scripts are practical when the same code is used in many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:
Example
You can place an external script reference in <head> or <body> as you like.
The script will behave as if it was located exactly where the <script> tag is located.
Use JavaScript within a webpage
Take your webpages to the next level by harnessing JavaScript. Learn in this article how to trigger JavaScript right from your HTML documents.
| Prerequisites: | You need to be familiar with how to create a basic HTML document. |
|---|---|
| Objective: | Learn how to trigger JavaScript in your HTML file, and learn the most important best practices for keeping JavaScript accessible. |
About JavaScript
JavaScript is a programming language mostly used client-side to make webpages interactive. You can create amazing webpages without JavaScript, but JavaScript opens up a whole new level of possibilities.
Note: In this article we’re going over the HTML code you need to make JavaScript take effect. If you want to learn JavaScript itself, you can start with our JavaScript basics article. If you already know something about JavaScript or if you have a background with other programming languages, we suggest you jump directly into our JavaScript Guide.
How to trigger JavaScript from HTML
Within a browser, JavaScript doesn’t do anything by itself. You run JavaScript from inside your HTML webpages. To call JavaScript code from within HTML, you need the <script> element. There are two ways to use script , depending on whether you’re linking to an external script or embedding a script right in your webpage.
Linking an external script
Usually, you’ll be writing scripts in their own .js files. If you want to execute a .js script from your webpage, just use <script> with an src attribute pointing to the script file, using its URL:
Writing JavaScript within HTML
You may also add JavaScript code between <script> tags rather than providing an src attribute.
That’s convenient when you just need a small bit of JavaScript, but if you keep JavaScript in separate files you’ll find it easier to
- focus on your work
- write self-sufficient HTML
- write structured JavaScript applications
Use scripting accessibly
Accessibility is a major issue in any software development. JavaScript can make your website more accessible if you use it wisely, or it can become a disaster if you use scripting without care. To make JavaScript work in your favor, it’s worth knowing about certain best practices for adding JavaScript:
Правильно подключаем Javascript в HTML
Javascript (часто можно увидеть сокращенную для написания версию JS) это язык программирования, который очень часто применяется в web-разработке. В этой статье мы расскажем, как подключить javascript к html документу. Сделать это можно двумя способами: встроить js-код непосредственно в сам html файл, так и с помощью подключения внешнего файла javascript
Первый способ: вставляем js-код прямо в html
Вставить javascript-код можно просто добавив его в любое место вашей html страницы, внутри тега <script>
Например, вот так может выглядеть ваша html-страница с подключенным js-кодом:
Вот мы и вставили js-код прямо в html файл. Но такое решение приемлемо, когда вы вставляете небольшой код, который нужно выполнить именно на этой странице. Тогда он не будет сильно тормозить загрузку страницы. Но лучше всего прописывать js-код в отдельном файле, а затем подключать его в html.
Второй способ: подключаем внешний файл
У этого метода есть ряд преимуществ.
- Разделение файлов упрощает дальнейшую работу с ними. Представьте себе, когда у вас несколько тысяч строк js-кода, очень легко во всем этом потеряться.
- Файлы js можно закешировать и тогда ваш сайт будет грузиться быстрее.
- Вы можете загружать js-код только после того, как вся ваша верстка прогрузится.
Давайте предположим, что у вас вот такая структура:
Тогда, чтобы подключить js файл script.js вам нужно прописать в html следующее:
Выглядеть это будет вот так:
Если же у вас немного другая структура или вам нужно подключить js файл в html документе, который не находится в корне, а лежит, к примеру в папке templates, то используйте символы «./» чтобы задать вложенность.
Для наглядности, предположим у вас такая структура:
Тогда путь к файлу script.js из contact.html будет такой:
Вот так можно подключать js к html файлам.
Кстати, обратите внимание, что и в первом и во втором способе можно не указывать type=»text/javascript» для тега script. Это уже необязательно.
How To Add JavaScript to HTML
JavaScript, also abbreviated to JS, is a programming language used in web development. As one of the core technologies of the web alongside HTML and CSS, JavaScript is used to make webpages interactive and to build web apps. Modern web browsers, which adhere to common display standards, support JavaScript through built-in engines without the need for additional plugins.
When working with files for the web, JavaScript needs to be loaded and run alongside HTML markup. This can be done either inline within an HTML document or in a separate file that the browser will download alongside the HTML document.
This tutorial will go over how to incorporate JavaScript into your web files, both inline into an HTML document and as a separate file.
Adding JavaScript into an HTML Document
You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code.
The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load.
Generally, JavaScript code can go inside of the document <head> section in order to keep them contained and out of the main content of your HTML document.
However, if your script needs to run at a certain point within a page’s layout — like when using document.write to generate content — you should put it at the point where it should be called, usually within the <body> section.
Let’s consider the following blank HTML document with a browser title of Today’s Date :
Right now, this file only contains HTML markup. Let’s say we would like to add the following JavaScript code to the document:
This will enable the webpage to display an alert with the current date regardless of when the user loads the site.
In order to achieve this, we will add a <script> tag along with some JavaScript code into the HTML file.
To begin with, we’ll add the JavaScript code between the <head> tags, signalling the browser to run the JavaScript script before loading in the rest of the page. We can add the JavaScript below the <title> tags, for instance, as shown below:
Once you load the page, you will receive an alert similar to this:

If we were modifying what is shown in the body of the HTML, we would need to implement that after the <head> section so that it displays on the page, as in the example below:
The output for the above HTML document loaded through a web browser would look similar to the following:

Scripts that are small or that run only on one page can work fine within an HTML file, but for larger scripts or scripts that will be used on many pages, it is not a very effective solution because including it can become unwieldy or difficult to read and understand. In the next section, we’ll go over how to handle a separate JavaScript file in your HTML document.
Working with a Separate JavaScript File
In order to accommodate larger scripts or scripts that will be used across several pages, JavaScript code generally lives in one or more js files that are referenced within HTML documents, similarly to how external assets like CSS are referenced.
The benefits of using a separate JavaScript file include:
- Separating the HTML markup and JavaScript code to make both more straightforward
- Separate files makes maintenance easier
- When JavaScript files are cached, pages load more quickly
To demonstrate how to connect a JavaScript document to an HTML document, let’s create a small web project. It will consist of script.js in the js/ directory, style.css in the css/ directory, and a main index.html in the root of the project.
We can start with our previous HTML template from the section above:
Now, let’s move our JavaScript code that will show the date as an <h1> header to the script.js file:
We can add a reference to this script to the <body> section, with the following line of code:
The <script> tag is pointing to the script.js file in the js/ directory of our web project.
Let’s consider this line in the context of our HTML file, in this case, within the <body> section:
Finally, let’s also edit the style.css file by adding a background color and style to the <h1> header:
We can reference that CSS file within the <head> section of our HTML document:
Now, with the JavaScript and CSS in place we can load the index.html page into the web browser of our choice. We should see a page that looks similar to the following:

Now that we’ve placed the JavaScript in a file, we can call it in the same way from additional web pages and update them all in a single location
Conclusion
This tutorial went over how to incorporate JavaScript into your web files, both inline into an HTML document and as a separate .js file.
Want to deploy your application quickly? Try Cloudways, the #1 managed hosting provider for small-to-medium businesses, agencies, and developers — for free! DigitalOcean and Cloudways together will give you a reliable, scalable, and hassle-free managed hosting experience with anytime support that makes all your hosting worries a thing of the past. Start with $100 in free credits!
Tutorial Series: How To Code in JavaScript
JavaScript is a high-level, object-based, dynamic scripting language popular as a tool for making webpages interactive.