Based on the answer of https://stackoverflow.com/a/31837264/4360308 I've implemented this functionality with Nodejs (+ express + cheerio) as follows:
HTML (index.html)
<div class="include" data-include="componentX" data-method="append"></div>
<div class="include" data-include="componentX" data-method="replace"></div>
JS
function includeComponents($) {
$('.include').each(function () {
var file = 'view/html/component/' + $(this).data('include') + '.html';
var dataComp = fs.readFileSync(file);
var htmlComp = dataComp.toString();
if ($(this).data('method') == "replace") {
$(this).replaceWith(htmlComp);
} else if ($(this).data('method') == "append") {
$(this).append(htmlComp);
}
})
}
function foo(){
fs.readFile('./view/html/index.html', function (err, data) {
if (err) throw err;
var html = data.toString();
var $ = cheerio.load(html);
includeComponents($);
...
}
}
append -> includes the content into the div
replace -> replaces the div
you could easily add more behaviours following the same design