The initial solution provided is in PHP because it is my preferred language. However, if you prefer to use JS, refer to the revised version below.
When working with PHP, you have the option to include a file containing functions and pass those functions as parameters:
index.php
<?php
include "topnav.php";
top("title");
?>
topnav.php
<?php
function top($title) {
?>
<div id="topNav">
<!-- Additional code here -->
<span id="title"><?= $title ?></span> <!-- Insert title here -->
</div>
<?php
}
?>
In my website development, I refrain from utilizing JS/jQuery to load page resources. Instead, I find PHP's include()
function more practical and hence use it extensively!
UPDATE
Upon reflection, implementing a similar approach in JavaScript is feasible albeit slightly more intricate. By defining a function in JS, you can invoke it directly within the page:
index.html
<script type="text/javascript">
$(function() {
$('#topnav').load('topnav.html');
$("body").append(top("title"));
});
</script>
topnav.html
<script>
// return or print out resource string
function top(title) {
return "<div id='topNav'>" +
"<!-- Additional code here -->" +
"<span id='title'>" + title + "</span>" +
"</div>";
}
</script>
UPDATE 2: In-depth explanation (as per request)
The JS example loads the resource file similarly to your method. However, instead of a plain HTML file, it involves a JS file. Once loaded, you are able to utilize the JS script. The additional script essentially allows for the utilization of a mostly predefined string, with the flexibility to incorporate variables (e.g.,
"<span id='title'>" + title + "</span>"
enables insertion of
title
).