Skip to content

Instantly share code, notes, and snippets.

@PuruVJ
Last active April 18, 2020 04:18
Show Gist options
  • Save PuruVJ/eb991f02814a3f5f2f962511774f4451 to your computer and use it in GitHub Desktop.
Save PuruVJ/eb991f02814a3f5f2f962511774f4451 to your computer and use it in GitHub Desktop.
import { h, FunctionalComponent, VNode, Build } from "@stencil/core";
const Helmet: FunctionalComponent = (_prop, children: VNode[]) => {
if (Build.isBrowser) {
for (let child of children) {
const tagName = child.$tag$.toString();
const attributes: {
[key: string]: string;
} = child.$attrs$;
// Some special cases
if (tagName === "meta") {
// It's a meta tag
// The only attribute I will watch out for is `name`
// Query
const specificMetaEl: HTMLMetaElement = document.querySelector(
`meta[name="${attributes.name}"]`
);
if (specificMetaEl) {
// Dont create new meta. Overwrite the original
specificMetaEl.content = attributes.content;
continue;
}
} else if (tagName === "title") {
document.title = child.$children$[0].$text$;
continue;
}
// Create the element
const el = document.createElement(tagName);
if (attributes != null) {
// Loop through the attributes given
for (let attr in attributes) {
el.setAttribute(attr, attributes[attr]);
}
// Finally set innerHTML
el.innerHTML = child.$text$;
}
// Append to head
document.head.appendChild(el);
}
}
return <span></span>;
};
export default Helmet;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment