This is a custom element / web component built using vanilla JavaScript to embed GistHub Gists into a webpage
without having to worry about the inline scripts which call document.write()
. It can be configured to lazy-load
using loading="lazy"
and styled with CSS through the github-gist
& github-gist::part(embed)
selectors.
Under-the-hood it creates an <iframe>
using:
<iframe srcdoc="..." sandbox="allow-scripts allow-popups" width="..." height="..." referrerpolicy="no-referrer"></iframe>
Since it uses srcdoc
, no additional requests are made beyond what the Gist embedding script would otherwise have loaded,
but this method does isolate the Gist from the rest of the page.
Note: setting height
or width
will be overridden if ::part(emebed)
sets either by CSS.
<script type="module" src="/main.js"></script>
<link rel="stylesheet" href="styles.css">
<github-gist user="shgysk8zer0" gist="68ee21d1d791754fb054dad0fbd7abda" loading="lazy">
<p>This content displays when the browser does not support custom elements.</p>
</github-gist>
import '/path/to/github-gist.js';
customElements.whenDefined('github-gist').then(/*...*/);
/* Do not display until custom element has been defined */
github-gist:not(:defined) {
display: none;
}
/* Style the <iframe> withing the Shadow root */
github-gist::part(embed) {
max-width: 100%;
}
<!-- Still need to load the script -->
<script src="/path/to/github-gist.js" defer></script>
<style>
github-gist::part(embed) {
max-width: 100%;
}
</style>
<github-gist user="shgysk8zer0" gist="68ee21d1d791754fb054dad0fbd7abda" loading="lazy">
<p>This content displays when the browser does not support custom elements.</p>
</github-gist>
import '/path/to/github-gist.js';
customElements.whenDefined('github-gist').then(() => {
const HTMLGitHubGistElement = customElements.get('github-gist');
const gist = new HTMLGitHubGistElement();
gist.loading = 'lazy';
gist.user = 'shgysk8zer0';
gist.gist = '68ee21d1d791754fb054dad0fbd7abda';
gist.width = 800;
gist.height = 500;
docuument.querySelector('.gist-container').append(gist);
});
loading
:lazy
oreager
, determining whether or not to lazy-load (defaults to eager)height
: Integer to set the height of the<iframe>
in pixelswidth
: Integer to set the width of the<iframe>
in pixelsfile
: Optionally display only a single file from a Gist by setting this to the filename