Last active
April 18, 2020 04:18
-
-
Save PuruVJ/eb991f02814a3f5f2f962511774f4451 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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