使用Gatsby加载一个外部JS文件的方法

194 阅读1分钟

在现代的JavaScript Web开发工作流程中,通过npm包来安装JavaScript是很常见的。

然而,有时我们必须包含一个外部的JavaScript文件,而现代的工具可能会让这一点变得有点困难。

特别是我需要在我的网站中包含一个来自Wistia的视频,在快速查看之后,一切看起来比我想要的要复杂。

Wistia给了我这个HTML片段来嵌入。

<script src="https://fast.wistia.com/embed/medias/VIDEOURL.jsonp" async></script><script src="https://fast.wistia.com/assets/external/E-v1.js" async></script><div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;"><div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><div class="wistia_embed wistia_async_VIDEOURL seo=false videoFoam=true" style="height:100%;position:relative;width:100%"><div class="wistia_swatch" style="height:100%;left:0;opacity:0;overflow:hidden;position:absolute;top:0;transition:opacity 200ms;width:100%;"><img src="https://fast.wistia.com/embed/medias/VIDEOURL/swatch" style="filter:blur(5px);height:100%;object-fit:contain;width:100%;" alt="" aria-hidden="true" onload="this.parentNode.style.opacity=1;" /></div></div></div></div>

在一个 "正常 "的HTML网站上,也许像我通常做的那样用Hugo建立,这将是非常简单的。

我只需将这段代码添加到我的页面。

但是在Gatsby页面,也就是一个React组件中?

我看了一些插件,但没有一个真正做到我想要的。

这个解决方案也许有点 "黑",但效果很好,我仍然觉得我可以控制正在发生的事情。

我把HTML代码添加为JSX,正确地转换了所有的HTML属性。class -> className,aria-hidden -> ariaHidden ,以及样式--使用像magic.reactjs.net/htmltojsx.h…这样的工具可以快速完成。

然后我把这段代码添加到gatsby-browser.js 文件中,以便在页面加载时添加我需要的脚本。

const addScript = url => {
  const script = document.createElement("script")
  script.src = url
  script.async = true
  document.body.appendChild(script)
}

export const onClientEntry = () => {
  window.onload = () => {
    addScript("https://fast.wistia.com/embed/medias/9rvl8vgrzg.jsonp")
    addScript("https://fast.wistia.com/assets/external/E-v1.js")
  }
}