How to include HTML script by using JavaScript



You know HTML pages is static. We can create dynamic website by mixing HTML and another language, such as PHP.

In PHP, we often create separate header & footer file, and then we dynamically change body content.

But what if we talk about simple offline web pages? For example, I want to make a navigation bar/menu that appears on every single offline HTML pages I have. Instead of creating same navigation bar/menu on each HTML file, I will create that navigation in a JavaScript file and use it on each HTML pages.

You can call this idea as “Embedding HTML in JavaScript” or “include HTML script by JavaScript” or whatever you want.

Lets go into the codes…

First, here is my navigation script in HTML:

<div>My Navigation</div>
<ul>
	<li>Menu 1</li>
	<li>Menu 2</li>
	<li>Menu 3</li>
</ul>

Based on this idea, I am going to embed this code into a JavaScript Variable.

I create a JavaScript file and create a function like this:

function writeNav(){
	var myNav = "<div>My Navigation</div><ul><li>Menu 1</li><li>Menu 2</li><li>Menu 3</li></ul>"
	document.write(myNav);
}

Now, on each HTML files I have to include that script file and then call writeNav() function on any location I want to include the navigation menu. For example:

<!DOCTYPE html>
<html>
	<head>
		<title>Include HTML by using JavaScript</title>
	</head>
	<body>
		<script>writeNav()</script>
		<p>This is my content and my navigation is included above!</p>
	</body>
</html>
loading...