I want to create a modular website with no frameworks or CMS nor server-side language. Also, I am doing simple use of the hashchange event to help the navigation.
The structure would be as follows:
- A basic container HTML page with 3 main areas: header, content, footer.
- Individual HTML files - one for each page - which would contain only the HTML to be inserted in the content part
- a JavaScript file with all the code needed
- a CSS file with all the styling
Please bear in mind that all the code below has been cleaned to illustrate the concept: the real code is more complex (e.g. the content of the header and the footer might as well be loaded with AJAX calls, some manipulations might occur to the DOM after the content has been put in place, handling AJAX failures, and so on).
A sample version of the HTML for the container page would be like:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Faux SPA</title>
<link rel="stylesheet" href="styles.css"/>
<script src="script/jquery/jquery-1.12.4.min.js"></script>
<script src="script/loader.js"></script>
</head>
<body>
<div id="viewPort">
<div id="header">
</div>
<div id="content">
</div>
<div id="footer">
</div>
</div>
<button onclick="setPageHash('Page1')">View 1</button>
<button onclick="setPageHash('Page2')">View 2</button>
</body>
</html>
A couple of sample HTML files for the content (obviously, the real-world content would be more complex):
Page1.html:
<div>
<img src="images/Image1.png" alt="">
</div>
And Page2.html:
<div>
Some text content
<br/>
second line of text content
</div>
Finally, the JavaScript code would be like:
var validHashes = ["Page1", "Page2"];
function page(pageName){
var newPageURI = pageName + ".html";
var container = "#content";
$.ajax(newPageURI).done(
function(content) {
putContentInContainer(container, content);
setPageHash(pageName);
}
);
}
function putContentInContainer(container, content) {
$(container).html(content)
}
function loadPageFromHash() {
var hashValue = window.location.hash || "";
var hashIsValid;
hashValue = hashValue.replace('#','');
hashIsValid = (validHashes.indexOf(hashValue)>=0);
if (hashIsValid) {
page(hashValue);
} else {
console.error("no valid HASH!");
}
}
function setPageHash(page) {
window.location.hash = page;
}
window.onhashchange = loadPageFromHash;
$().ready(function() {
loadPageFromHash();
});
So, my questions are:
- Is there any disadvantage in loading the HTML this way?
- I know that the HTML files with the content will not be valid HTML files because of the missing tags (e.g.
body
,html
, etc.): would that represent a problem? - Is there anything else I am missing for the whole hashchange subject?