1
votes

I cannot find a way to embed a github gist in my local svelte application.

Whatever I do, the client console throws me a Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened. error or simply doesn't display anything.

This is maybe evident, but it seems github embedded gists use document.write to create the gist element at the script emplacement while the document is loaded

This issue on svelte repo seems related, but only talks about the demo REPL of the svelte website...

What I tried so far :

  • just embed the script tag given by github in my page.svelte -> error above
  • embed it in the template index.html for testing -> this worked but obviously you have the gist at the top of any page...
  • create a Gist.svelte component with the following code -> error above
<!-- Gist.svelte -->
<script>
  export let gistUrl = ""

  import { onMount } from 'svelte'

  let container;

  onMount(() => {
    const child = document.createElement('script')
    child.src = gistUrl + ".js"
    //child.defer = true
    container.appendChild(child)
  })
</script>

<div bind:this={container}/>
<!-- page.svelte -->
<!-- ... -->
  <Gist gistUrl="the_gist_url"/>
<!-- ... -->

PS : I did not dare open a new issue about this before asking stackoverflow.

2

2 Answers

1
votes

You can work around this by rendering the Gist in an <iframe>:

<!-- Gist.svelte -->
<script>
  export let gistUrl = ""

  import { onMount } from 'svelte'

  let frame;
  onMount(() => {
    frame.srcdoc = `<script src='${gistUrl}.js'><${""}/script>`;
  });
</script>
<style>
  iframe {
    border: 0;
    width: 100%;
    height: 100%;
  }
</style>
<iframe src="about:blank" bind:this={frame} title="Gist"></iframe>

Try it in the REPL

0
votes

This problem is not svelte specific. An asynchronously loaded script like the embedded github gist is going be run after the document (created by svelte) has been fully parsed and closed. This is why placing the tag in the index.html works (because document is still open). For more information check this stackoverflow question