svelte:嵌入式 github gist 抛出无法在“文档”上执行“写入”

问题描述

我找不到在本地 svelte 应用程序中嵌入 github gist方法

无论我做什么,客户端控制台都会向我抛出一个 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. 错误或根本不显示任何内容

这可能很明显,但似乎 github 嵌入式 gist 使用 document.write 在加载文档时在脚本位置创建 gist 元素

This issue on svelte repo 貌似有关系,但只讲svelte网站的demo REPL...

到目前为止我尝试过的:

  • 只是将 github 给出的 script 标签嵌入到我的 page.svelte -> 上面的错误
  • 将其嵌入模板 index.html 以进行测试 -> 这有效,但显然您在任何页面的顶部都有要点...
  • 使用以下代码创建一个 Gist.svelte 组件 -> 上面的错误
<!-- 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 : 在询问 stackoverflow 之前,我不敢就此开新 issue。

解决方法

您可以通过在 <iframe> 中呈现 Gist 来解决此问题:

<!-- 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

,

这个问题不是特定的。在文档(由 svelte 创建)完全解析和关闭后,将运行异步加载的脚本,如嵌入式 github gist。这就是将标签放在 index.html 中的原因(因为文档仍然打开)。有关详细信息,请查看此 stackoverflow question