I'm redesigning application that could be a good fit for SPA. After reviewing the code I found that previous developers used JQuery/JavaScript load() method to include .html files. For example they have header.html and footer.html. On page load .html are loading in div containers. Example:
<!DOCTYPE html>
<html>
<head>
<title>App Home Page</title>
</head>
<body>
// Body content
<script>
$(function () {
$('#header').load('includes/header.html');
$('#footer').load('includes/footer.html');
});
</script>
</body>
</html>
In this case loading .html doesn't have any impact on JavaScript events since none of the elements in these two files have events. In case for example if I put onClick function in one of the elements in header.html that will be a problem. The DOM content will load before script on the bottom of the body tag. I have questions about this methods:
- Is it a good approach to load
.htmlfiles using JavaScript for this purpose? - Is there any reason to load
.htmlwith JavaScript other than cleaner code and easier maintenance? - If there are
benefits of loading
.htmlwith JavaScript, how to prevent race condition in case where DOM is loaded before script content?
I'm trying to understand why this approach would be a good option and if that is a good practice now days in Web Development of Single Page Applications. Another thing that I forgot to mention is that I only use front end languages for this project. There is no server-side language involved.