This library creates an easy interface to build very simple static web components.
At Link Society, we use it within our Hugo websites to add interactivity to some parts.
This library has no dependency but requires browser support of the following standards:
To integrate the script (less than 1kb) within your HTML page, copy the following code:
<script type="application/javascript" crossorigin="anonymous" src="https://link-society.github.io/micro-web-component/index.js"></script>
First create your template:
<template id="foobar-tmpl">
<div class="foo"></div>
<div class="bar"></div>
</template>
Finally, create your Web Component:
<script type="application/javascript">
MicroWebComponent.extends({
tag: 'foobar',
template: 'foobar-tmpl',
render(instance) {
instance.querySelector('.foo').innerHTML = 'foo';
instance.querySelector('.bar').innerHTML = 'bar';
}
});
</script>
Now you can use your Web Component everywhere in the page:
<foobar></foobar>
If you included jQuery, you are free to use it:
<script type="application/javascript">
MicroWebComponent.extends({
tag: 'foobar',
template: 'foobar-tmpl',
render(instance) {
$(instance).find('.foo').html('foo')
$(instance).find('.bar').html('bar')
}
});
</script>
If you are, like us, using Hugo to generate your static website and have some
data in the data
folder:
# data/foobar.toml
[foo]
text = "hello there"
[bar]
text = "general kenobi"
You can include that data in your template:
<template id="foobar-tmpl">
<div class="container" data-foobar="null">
<div class="foo"></div>
<div class="bar"></div>
</div>
</template>
And fetch it within your web component:
<script type="application/javascript">
MicroWebComponent.extends({
tag: 'foobar',
template: 'foobar-tmpl',
render(instance) {
const foobar = JSON.parse(instance.querySelector('.container').dataset.foobar)
// or with jQuery:
//
// const foobar = $(instance).find('.container').data('foobar')
instance.querySelector('.foo').innerHTML = foobar.foo.text
instance.querySelector('.bar').innerHTML = foobar.bar.text
}
});
</script>
This library is released under the terms of the CC0 license, in other words: the public domain.