HTML - javascript

How to Add Javascript to HTML

Javascript is a versatile programming language and gives you the ability to create content that changes when users interact with a web page. But, to make those changes happen, you must be sure to make Javascript part of your web pages and add it to HTML.

The Javascript standard specifies the syntax of the Javascript language, but it does not describe HTML or explain how to add Javascript to HTML. The HTML standard dictates that you must use the script tag to include Javascript code inside web pages.

To help you along your journey to learning programming languages, we’ll describe how to add Javascript to HTML using the script tag, why the placement of the script tag affects how Javascript executes, and how to manage the Javascript you add to your web pages.

The Script Tag

The script tag is the correct method for adding Javascript to HTML. HTML cannot access or change Javascript code inside a script tag, but Javascript can access or change HTML. Variables created within one script tag cannot be accessed by another script tag somewhere else on a web page.

There are two different ways to insert Javascript into a script tag: writing code directly inside the tag or specifying the path to an external Javascript file.

Writing code directly into a script tag is best for small code snippets that don’t require external libraries, significant maintenance, or re-use on other web pages. The following Javascript snippet changes the variable is_udacity if the page loads on Udacity’s specific web address.

<script>
let is_udacity = false;
if (window.location.href === "https://udacity.com") {
    is_udacity = true;
}
</script>

Longer pieces of Javascript code are best embedded into a script tag using the src attribute. This attribute is best used for long scripts that developers may reuse in the future.

The value of the src attribute must be a valid URL to a Javascript code file (which must have a .js extension), and there must be no code inside the script tag itself. This method of embedding code is also how developers incorporate Javascript frameworks like JQuery, Angular, and React into web pages.

<script src="https://example.com/example.js"></script>

Adding Javascript to HTML

Javascript affects the HTML in web pages differently depending on where it’s placed in the page. This happens because web pages execute Javascript in order.

You must define Javascript frameworks or functions before using code that relies on them or the Javascript interpreter will not recognize the variables or functions you’re using, potentially causing execution errors. Javascript order affects Javascript output and the Javascript Document Object Model (DOM).

Javascript In the Page Head

Placing HTML in the page head is useful for long scripts that hold functions you reuse often, like Javascript frameworks. Javascript scripts in the page head load before the page body is visible, so any functions loaded through the page head become visible to Javascript script tags inside the page body.

While loading Javascript scripts in the page head, the content of the page body is not visible. Be careful to balance Javascript content with loading time: If it takes too long for these scripts to load, web users might think there is something wrong with the page and leave.

Most developers follow a de facto standard of loading all scripts and content for web pages within 3 seconds. Studies have shown that web users rarely stay on a web page if it takes longer than 3 seconds to load.

<!doctype html>
<html lang="en">
    <head>
        <title>Javascript Head Example</title>
        <script src="https://example.com/framework.js"></script>
    </head>
    <body>
        <p>Content</p>
    </body>
</html>

After the Page Body

Placing Javascript after the page body is useful for scripts that must affect page content after everything is loaded. Since the entire page loads before executing these scripts, users can see page content more quickly.

<!doctype html>
<html lang="en">
    <head>
        <title>Javascript Head Example</title>
    </head>
    <body>
        <p>Content</p>
        <script src="https://example.com/script.js"></script>
    </body>
</html>

Everywhere Else

You can put script tags in the page head and page body simultaneously, in any order you need. Try to plan Javascript placement so it minimizes the page load time and is structured so all necessary functions are still available for the elements they affect.

<!doctype html>
<html lang="en">
    <head>
        <title>Javascript Head Example</title>
        <script src="https://example.com/framework.js"></script>
    </head>
    <body>
        <p>Content</p>
        <button>Dynamic Button</button>
        <script src="https://example.com/buttonScript.js"></script>
        <p>More Content</p>
        <script src="https://example.com/script.js"></script>
    </body>
</html>

Managing Javascript Added to HTML

Adding Javascript to HTML involves more than just using the script tag and putting it in the right place for your needs. Javascript affects web accessibility and may vary between browsers. People also sometimes use Javascript in places where it isn’t necessary.

Accessibility

Using or placing Javascript incorrectly can cause major difficulties for people with disabilities who navigate the web. Screen readers often do not react when Javascript dialog boxes pop up, and without accessibility attributes in HTML, screen readers may not realize when the content of a page changes.

Accessible Javascript involves manipulating HTML and CSS for maximum usability and clarity. Although the topic is too broad to cover in detail here, you should strive to make your Javascript accessible wherever it resides on a web page.

Browser Variations

Modern web browsers have relatively consistent implementations of Javascript, so developers can usually be sure that a method will work the same way on one browser as it does on another. Sometimes, though, you may need to support older browsers that don’t implement newer Javascript capabilities.

In those cases, you should insert a polyfill, a piece of Javascript code that imitates the action of newer Javascript features while using older Javascript syntax. Polyfills tend to be long, complicated pieces of code, so adding them into a page at a point where they won’t slow down loading or execution times is preferable.

Necessary Javascript

It’s easy to assume that Javascript is a solution for every problem, but not every dynamic thing a web page does requires Javascript to work. For example, it’s common in many modern web pages to rely on Javascript to open a dropdown menu, but the CSS :hover selector can do the same thing with much less code.

Be sure that Javascript is the proper tool for the dynamic functionality your page needs. Some modern HTML elements have built-in dynamic functionality, so Javascript is not necessary in those cases. Don’t force Javascript in when it’s not needed.

Conclusion

The script tag is a basic Javascript concept that provides multiple options for when you want to add Javascript to HTML. You can write small pieces of code that fit easily into the script tag or embed larger pieces of code with the src attribute.

The position of your script tag in HTML is important; it impacts how quickly your pages load and could make significant changes to the HTML structure. Be aware of where your script tags are and how they might affect the rest of the web page read after them.

Most importantly of all, remember that any Javascript you add to a page must be as robust as possible. Don’t forget to consider whether your Javascript meets accessibility standards, whether it functions differently in older browsers, or whether your web page actually needs it.

Enroll in our Intro to Programming Nanodegree Program today to learn more about adding Javascript to HTML and other programming concepts.

Jessica Reuter Castrogiovanni
Jessica Reuter Castrogiovanni