Use Gatsby to load external JS files

In modern JavaScript web development workflows, it is very common to install JavaScript through the npm package.

However, sometimes we have to include an external JavaScript file, and modern tools may make this operation somewhat difficult.

In particular, I need to include videos from Wistia on my website, and after a quick glance, everything looks much more complicated than I want.

Wistia gave me this HTML code snippet to be embedded:

<script src="" async></script><script src="" 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="" style="filter:blur(5px);height:100%;object-fit:contain;width:100%;" alt="" aria-hidden="true" onload=";" /></div></div></div></div>

On a "normal" HTML site, perhaps like I usually build with Hugo, this is simply too simple.

I just added this code to my page.

But in the Gatsby page, which is the React component?

I looked at some plugins, but no one really did what I wanted.

This solution may be a bit "tricky", but it works like a charm, and I still feel like I can control what is happening.

I added the HTML code as JSX, all HTML attributes can be converted correctly:class -> className,aria-hidden -> ariaHiddenAnd style-use similar it fast.

Then I add this code togatsby-browser.jsFile to add the script I need, the page loads:

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

export const onClientEntry = () => { window.onload = () => { addScript(β€œ”) addScript(β€œ”) } }

Download mine for freeJavaScript beginner's manual

More js tutorials: