Home / Blog /
Inline JavaScript in HTML: Don’t do it, unless you like really, really bad code
//

Inline JavaScript in HTML: Don’t do it, unless you like really, really bad code

//
Tabnine Team /
6 minutes /
June 24, 2020

Modern code has moved away from manual coding and into optimized structures that provide a framework for effective code creation processes. Especially, for front end code.

Writing inline JavaScript is one of the many things you learn when you want to tinker with how HTML behaves. However, writing JavaScript straight into your HTML pages is not considered a best practice. In fact, it’s considered very 90s by today’s coding standards.

Just because you can do it doesn’t mean that you should. 

Why should you not use inline Javascript in HTML?

Because JavaScript was created in a different era. However, it’s evolved beyond its original envisioned scope, permeating through into places and spaces like mobile devices, tv screens, and wearable gadgets.

In the world of JavaScript, the web, and its relationship with DOM manipulation, we’ve come far with architectural setups, version releases, and away from the manual and traditional way of writing inline JavaScript

just don't do inline javascript in html

What inline JavaScript looks like

But before we dive into the alternatives of writing inline JavaScript, here’s what it looks like.

You have an HTML page — with the base structure looking something like this:

<!DOCTYPE>
<html>
<head></head>
<body></body>
</html>

When you want to add an external JavaScript sheet, you use the <script src=""> tag, with a reference to where you file is in between the ” ” .

A browser will read your HTML document from top to bottom, pulling and loading your JavaScript file at the location and initialized the script accordingly. This means that if you put your JavaScript call at the very top and within the head area, your script will execute immediately, right before any of the DOM is loaded.

For some external scripts, it requires all the DOM elements to be loaded first, and hence the recommendation is to put the script src call right at the bottom.

When you write inline JavaScript, what you’re doing is similar to what the script src tag is doing, except the code is right inside the HTML file, rather than having to be called externally

To do this, it looks something like this:

<script>

//your JavaScript code here

</script>

When you put your JavaScript code inside <script> tags, it lets the browser know that the code in between is to be interpreted as JavaScript. If you don’t do this, the code will be treated and printed as plain text.

The pros, the cons, and the horror stories of inline JS

Inline scripts are often seen in spaces such as Google Analytics tracking codes, site verifications and ownerships for webmaster tools, and initializing and setting parameters of external scripts. 

Here’s one example:

<!DOCTYPE html>
<html>
<head>
    <title>Inline JavaScript</title>
    <meta charset="utf-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1">
    <link rel="stylesheet"
          href=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h1 style="text-align:center;color:green;">
          GeeksforGeeks
      </h1>
        <form>
            <div class="form-group">
                <label for="">Enter Your Name:</label>
                <input id="name"
                       class="form-control"
                       type="text"
                       placeholder="Input Your Name Here">
            </div>
            <div class="form-group">
                <button id="btn-alert"
                        class="btn btn-success btn-lg float-right"
                        type="submit">
                     Submit
                </button>
            </div>
        </form>
    </div>
    <script>
        var user_name = document.getElementById("name");
        document.getElementById("btn-alert").addEventListener("click", function(){
            var value=user_name.value.trim();
            if(!value)
                alert("Name Cannot be empty!");
            else
                alert("Hello, " + value + "!nGreetings.");
        });
    </script>
</body>
</html>  

While these implementations are innocent enough, they do become cumbersome to maintain over time if there are multiple pages involved. This becomes especially hard when the code is passed through multiple developers.

The code can grow into a large decentralized mammoth with potential for conflicts, and a unified approach to doing things.

JavaScript essentially has two main abilities — the first being the ability to call and push data over to a server, and the second being the ability to manipulate the DOM based on actions, reactions, and inputs

When you start doing these things inline, it can cause page stability issues, in addition to duplicate code and potential long term headaches for the developers involved due to the manual nature of inline JavaScript.

html javascript and css types

Do you stay updated with the latest advancements and trends in software development?

It’s essential to remain informed about new technologies and practices to excel in this constantly evolving industry. Learn how you can leverage AI to optimize your software engineering in 2023.

What Angular does with JavaScript

Angular is a JavaScript framework that turns coding into a highly organized and architectural packaged piece of code. On the surface, it’s single paged. This means that everything is rendered via the compiled JavaScript that calls your server for portions of your DOM and stitches them together to form a complete view.

This is useful for handling data, creating a level of persistence, reducing the amount of code required, and as a side effect, reduce the potential of duplicated code. While duplicated code is not completely eliminated and depends on how the developer structures the code, it’s a much better approach than inline JavaScript. 

However, this can cause issues for things like Google analytics, which works through an inline approach and requires the page to refresh in order to push over data for tracking.

When you’ve got a single page application, your root index.html never had refreshes, unless you’ve got a special setup for it to happen with some enforced persistence for the app’s general data. 

For external scripts to work properly, you can either find a module that supports it in the npm open-source space, or import the script into your Angular app and use the life cycle hooks to push or pull relevant data to the right places. 

single page apps solve for inline js in html

What React does with JavaScript

Another popular JavaScript incarnation is React. This front end library is a popular alternative to Angular. While Angular has a TypeScript layer between the JavaScript and the code you create, React uses JSX, which is a syntax extension of JavaScript.

What happens here is that you are essentially putting JavaScript and DOM elements in one file, for it to be rendered by React

Like Angular, React can also be configured into a single page application (SPA), or ported over as widgets that sits inside other DOM-based applications. 

However, unlike Angular, where there is a clear separation of code types (HTML, CSS and JavaScript), React inverses the concept of separation of concerns by putting everything you need into the same space. So rather than having to bounce between multiple files, React’s JSX returns everything back into it’s original HTML and JavaScript relationship days and makes the code inline once again.

However, rather than marking out your scripts in between script tags, you are marking out your HTML instead. With React, your JavaScript becomes the center of attention and your HTML becomes the ‘inline’ equivalent element.

How JavaScript fits into everything

When it comes to the web, DOM manipulation, and creating user experiences, JavaScript is the most widely supported language to do so. 

However, the scripting language has grown up since it’s original days of writing JavaScript code directly in the HTML. This in part, is because how we use the web has also dramatically changed.

While inline scripts can come in useful for backend based renderings of HTML pages, it’s still not widely recommended for code reliability, readability, and cleanliness reasons. There are better ways to import, implement, and use JavaScript.

As we move into an API based architecture for application stacks, the demarcation between front-end and backend creates clear boundaries between the types of architectures required to create a robust piece of software that are able to effectively integrate with one another.

If you are using a framework or library like Angular or React, using the traditional <script> tag to place inline JavaScript snippets will often lead to breakages in your applications. Why? Because it’s violating the preset rules that make the framework or library special. It’s best to keep to the rules of your framework or library so that you don’t violate their state management flows.

Why? Because state management is the thing that keeps your app’s data intact. When you start using inline JavaScript that sits outside the flow, you risk creating leaks and introduce avoidable weaknesses to your app.

new javascript framework and its impact on javascript developers

While it all boils down to JavaScript, the point of using a framework or library is to help you structure and organize your code in a way that allows you to manage the flow of data and any transient persistence on the page, or part of the page. When you use inline JavaScript in a way that’s not endorsed by the architectural framework or library, you increase the chances of it breaking when things are required to change.

Final thoughts

Inline JavaScript is not evil — but there’s a time and place for everything. While it was popular in the days before Angular and React rose to the peaks of its current adoption, the usage of pure inline JavaScript is on the decline.

Just because you can do it and in relative ease, it doesn’t mean that you should. 

Using inline JavaScript might be justifiable for small snippets that isn’t expected to be repeated elsewhere, or are incorporated into parts of the header — but even then, it is not advisable unless it is part of an initialization process to make your application work.