BLiu1's Blog

Server Side & Client Side Includes

January 11, 2014

Oftentimes we need something similar to appear in many webpages. Some examples would be a quote-of-the-day or a navigational menu or anything else that needs to be consistent over many webpages. A solution to this is includes. There are many ways to include a separate text or HTML file in a webpage.

PHP Includes

PHP has an include() function. It tells the server to insert HTML, PHP script, or plain text into a webpage before it reaches the client (web browser). You would use it like this.

<?php
	include('file.php');
?>

You can use PHP extensions and extension .inc for includes. This is the kind of include I use in my webpages because you can do scripting in PHP as well.

SHTML Includes

Files with a special extension, usually .shtml, .stm, or .shtm, can be used for server side includes. The way you would include something with these is this:

<!--#include virtual="../file.txt" -->

JavaScript Client Side Includes

A simple way to include HTML is to convert it to a string and inject it with JavaScript into the DOM.

Your HTML could have an element for the JavaScript to inject into.

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>JS Includes</title>
	<script src="include.js"></script>
</head>
<body>
	<h1>JS Includes</h1>
	<div id="content"></div>
</body>
</html>

The JavaScript for it could look like this.

var txt = "<h1>Lorem Ipsum</h1>";
txt = "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>";
txt += "<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>";
txt += "<p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p>";
txt += "<p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>";
txt += "<a href='http://lipsum.com'>Lorem Ipsum Generator</a>";
document.getElementbyId("content").innerHTML = txt;

You could also append stuff to the body like this.

var moreText = "<div>Another Div</div>";
document.body.innerHTML += moreText;

Tags:

Comments

BLiu1's Blog - Server Side & Client Side Includes

comments powered by Disqus
eXTReMe Tracker