I’m working on a mobile app with capacitor and vanilla Js and I’m following a tutorial to help me set it [up][1]. In the tutorial, it is indicated that to make several pages of our app, we copy and paste the code in each of the pages (index.html, info.html), but I find that a lot of code is duplicated like the header, footer, etc.
Example of index.html:
<!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8" />
// a lot of header code which we want to import via another source
</head>
<body>
<custom-navbar>
<h1 slot="title">My capacitor app</h1>
<div slot="end">
<a href="/info.html"><button>Info</button></a>
</div>
</custom-navbar>
<script src="./js/navbar.js" type="module"></script>
</body>
</html>
and I’m looking to load the code that looks similar from a single file a bit like PHP’s include(‘my_file.php’) ($vars) so as not to duplicate the same code in a page.
For example, in my index I would like the header to be loaded from an external file that I can simply import a bit like the class constructor method import in our main html file of a .custom-header.js file which looks like this
`window.customElements.define(
'custom-header',
class extends HTMLElement {
constructor() {
super();
SplashScreen.hide();
const root = this.attachShadow({ mode: 'open' });
root.innerHTML = `<style>
:host {
font-family: -apple-system, BlinkMacSystemFont,....";
display: block;
width: 100%;
height: 100%;
} etc....`
And import it in the main html file like this:
<!doctype html>
<html lang="en" dir="ltr">
<custom-header></custom-header>
<body>
<custom-navbar>
<h1 slot="title">My capacitor app</h1>
<div slot="end">
<a href="/info.html"><button>Info</button></a>
</div>
</custom-navbar>
<script src="./js/navbar.js" type="module"></script>
</body>
What I’ve found so far that works is a javascript import and the document.getelementbyID().innerHTML method as shown here:
const header = `
<head>
<meta charset="UTF-8" />
//.. all our header html code
<meta name="theme-color" content="#31d53d" />
</head>
`
document.getElementById("header").innerHTML = header;
and in our index.html put an id where we want to have the header code:
<!doctype html>
<html lang="en" dir="ltr">
<div id="header"></div>
<body>
<!-- Our specific body code-->
<script src="./custom-header.js" type="module"></script>
But I would like to know if there is a way to do this with classes and constructors like the example I mentioned earlier. Thanks
[1]: https://ionic.io/blog/create-powerful-native-mobile-apps-with-capacitor-vanillajs
3