Created
April 20, 2021 14:15
-
-
Save aziis98/fbb7c3047411819b2d8c7a41e14e786b to your computer and use it in GitHub Desktop.
A Javascript function to embed an HTML component inside a scirpt tag that also loads all necessary JS in the right order
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
| const TICK = '`'; | |
| const componentEmbedTemplate = ({ uid, code }) => ` | |
| <div class="embed"> | |
| <script id="embed-${uid}"> | |
| (async function() { | |
| const $self = document.getElementById('embed-${uid}'); | |
| const $embedContainer = document.createElement('div'); | |
| $embedContainer.classList.add('container'); | |
| const $shadow = $embedContainer.attachShadow({ mode: 'open' }); | |
| const fix1 = '<' + '/script>'; | |
| const fix2 = '${TICK}'; | |
| const html = ${TICK}${code.replaceAll('`', '${fix2}').replaceAll('</script>', '${fix1}')}${TICK}; | |
| $shadow.innerHTML = html; | |
| $self.parentElement.insertBefore($embedContainer, $self); | |
| const $scripts = $shadow.querySelectorAll('script'); | |
| for (const $s of $scripts) { | |
| if ($s.src) { | |
| const $dy = document.createElement('script'); | |
| $dy.src = $s.src; | |
| document.head.appendChild($dy); | |
| await new Promise((resolve) => { | |
| $dy.onload = resolve; | |
| }); | |
| } else { | |
| console.log($s.innerHTML); | |
| eval('const document = $shadow;\\n' + $s.innerHTML); | |
| } | |
| } | |
| })(); | |
| </script> | |
| </div> | |
| `; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment