Reputation: 181
In total, I have 3 pages: index.html
, sketch.html
and user-profile.html
.
All of them have the same navbar (I just copied and pasted the nav
element for now), but I now realize that this is not the best idea.
The navbar has its position on the screen (HTML), the styling (CSS) and the login and register functionality (Javascript). How would I go about combining these for three different pages?
Since I am using a module bundler (Parcel.js), I was thinking of creating a .js
and .css
for EACH page. So for example the folder index
will have:
index.css
-> will import the necessary elements, example (pseudo-code): import "../styles/navbar.css"
index.js
-> will import the necessary scripting for logging and registering, example: require("..scripts/sessions.js");
index.html
-> will import those two files
... and do the same for each page.
But... is that really necessary? Is there a better way of doing this?
Upvotes: 0
Views: 6722
Reputation: 482
There is a dirty-but-working vanilla JS hack:
async function includeHTML() {
const includes = document.getElementsByTagName('include');
[].forEach.call(includes, include => {
let filePath = include.getAttribute('src');
fetch(filePath).then((file) => {
file.text().then((content) => {
include.insertAdjacentHTML('afterend', content);
include.remove();
});
});
});
};
Now, you can create element like this: <include src="navbar.html"></include>
Just run the function. If you add some javascript functionality, use Promises so that your code executes after this function.
includeHTML()
Upvotes: 1
Reputation: 350
Honestly, there's not an easy way to do this with vanilla Javascript. You basically have to either create the navbar using JS, which can then be imported to each page, or you have to copy and paste it.
The industry solution to this problem is to use React, Vue or Angular, all technologies which allow you to create and reuse JSX 'components'. In other words, in React, you could create a navbar component, which could easily be imported in any 'page' of the website. But with vanilla HTML/Javascript, it's really not an option.
Upvotes: 3