Wednesday, July 6, 2022

Best Practices for Combining JavaScript with HTML

This article will help you discover some of the best practices for combining JavaScript with HTML

Generate Dynamic HTML

Whenever a Web page is loaded, the browser creates a Document Object Model of the page; the HTML documents can be easily viewed and managed using the HTML DOM which shows the HTML document as a tree structure. We can use the Document object to access all HTML elements (as node objects) in a page, so we can also add or remove element. JavaScript has some very useful and often-used functions that we will utilize next. In the example below, createElement() method creates an Element Node with the specified name and the appendChild() method appends a node as the last child of the node.

In the example below, we will create a dynamic HTML contact form using the method presented above:

   <title>Contact Form</title> 

border: 1px solid #ccc;
width: 300px;
height: 550px;
padding: 0px 50px 15px;
box-shadow: 0 0 50px #00cd00;
border-radius: 10px;

background-color: #e55ea2; 
height: 8px; 
border: 0; 

float: left;
font-size: 20px;
color: #993f6c; 
font-weight: bold;

height: 35px;
margin-bottom: 25px;
border:2px solid #e55ea2;

border:2px solid #e55ea2;
margin-bottom: 25px;
margin-top: 10px;
height: 100px;

padding: 10px 45px;
background-color: #e55ea2;
border: none;
color: white;
font-size: 20px;
font-weight: bold;
cursor: pointer;



   <div id="main">

   <div id="myform"></div>
var x = document.getElementById("myform");

var createform = document.createElement('form'); // Create New Element form
	createform.setAttribute("action", "");        // Setting action Attribute on form
	createform.setAttribute("method", "post");  // Setting method Attribute on form

var heading = document.createElement('h2'); // Heading of form
	heading.innerHTML = "Contact Form ";  

var line = document.createElement('hr');  //giving horizontal row after heading

var linebreak = document.createElement('br');

var namelabel = document.createElement('label'); // Create Label for name field
	namelabel.innerHTML = "Name : ";            // Set Field Labels

var inputelement = document.createElement('input'); // Create input field for name
	inputelement.setAttribute("type", "text");  
	inputelement.setAttribute("name", "dname");

var emaillabel = document.createElement('label');  //Create Label for email field
	emaillabel.innerHTML = "Email : ";

var emailelement = document.createElement('input'); // Create input field for email
	emailelement.setAttribute("type", "text");
	emailelement.setAttribute("name", "demail");

// Create Textarea
var messagelabel = document.createElement('label'); 
	messagelabel.innerHTML = "Message : ";

var texareaelement = document.createElement('textarea'); 
	texareaelement.setAttribute("name", "dmessage");

// Create Submit Button
var submitelement = document.createElement('input'); 
	submitelement.setAttribute("type", "submit");
	submitelement.setAttribute("name", "dsubmit");
	submitelement.setAttribute("value", "Submit");


The output of the above contact form generated dynamically is:

Optimize JavaScript Placement

Another good practice in using JavaScript with HTML is to place your JavaScript at the end of your HTML file if it is possible, between <script> tags, before the closing </body> tag, as you may notice from the above example. It allows all the DOM elements to fully load before loading the JavaScript which addresses them, that means that a great part of page content, such as tables, images or text, to be loaded and performed first; so, in this point, the hard JavaScript can begin loading close to the end.

Calling Function in JavaScript File from HTML onClick Event

A function contains some code which will be executed by an event or a call to that function and it is never executed before it is called. The JavaScript functions should be defined between <script>…</script> tags, but you can also add function from a separate JavaScript file and included in the html page. In the example below, we will create the myTestFunction, that has three arguments, and which will be called from the on Click events on a button click.

<!DOCTYPE html>

<p>Click "Submit" button to call a function with arguments</p>

<button onclick="myTestFunction('Johnny','[email protected]','some text')">Submit</button>

<p id="test"></p>

function myTestFunction(name,email,message) {
    document.getElementById("test").innerHTML =
    "Name: " + name + ", Email: " + email + " Message: " + message+".";


The output of the above listing is:

Keep DOM Access to a Minimum

Accessing the DOM in browsers is a slow and expensive process, because DOM is a very complex API that rendered in browsers can take up a lot of time and it uses a lot of processor power (CPU). You can see this when running complex Web applications and your computer is already exhausted with other jobs: changes take longer or get shown half page and so on. To minimize the access of your DOM, you can assign a node to variables that you will use many times in the application, that avoids traversing the tree each time the document is managed. To make sure that your code is fast and doesn’t slow down the browser, keep DOM access to minimum, instead of constantly creating and applying elements, it is recommended to use a tool function that converts a string into DOM elements and call this function at the end of your generation process. Shadow DOM is a library that allows the Web browser to render DOM elements without putting them into the main document DOM tree.

JavaScript Naming Conventions

Some of the main naming conventions rules for setting names and identifiers to enable the readability, maintainability and consistent code are listed below:

  • Avoid single letter names and do not use _ underline as the first or last character of a name; use a leading underscore _ when naming private properties
  • Use CamelCase when naming objects, functions and instances
  • Name your functions, all functions should be declared before they are used and there should be one space between the ) right parenthesis and the { left curly brace that begins the statement body. (per example: function test(d) { )
  • Avoid excessively long lines (<80 characters)
  • Be generous with comments, it is useful to place information that will be read later by someone else
  • All variables should be declared before used; each variable assignment should be declared on a separate line, use of global variables should be minimized.
  • All code must indent using two (2) space characters, all code must not indent using tab characters, all code must not end with a whitespace.

Minify the Files Sizes

Another good practice of optimize the file request and speed up the page load is to reduce the sizes of different file. The minify process consists of removing all unnecessary characters from the source code without changing its main goal, like: white space characters, new line characters, comments. The minified source code is really useful because it reduces the amount of data that needs to be transferred. There are many tools meant to do this job, such as Google Closure Compiler, JSMin, Yahoo YUI Compressor and so many more. For minification of HTML code, there are the following tools: HtmlCompressor, HTMLMinifier and WebMarkupMin.


In order to develop a consistent Website that is fast, easy to modify, understand and maintain, you should keep in mind the basic rules described in this article.

Popular Articles