How to include jQuery in a Gatsby.js project?

I've been experimenting with gatsby.js for a while and everything is going well except for this issue, i cannot include jQuery scripts unto the app so that it loads after the gatsby app has been rendered, i've the included script tags unto the html.js file and loaded it but it seems that the code is executed before react renders the content unto the screen i've tried using simple-load-script as well to include it on the componentDidMount method on the html.js app. But with no luck, here is the source code to my html.js file:

html.js

import React from "react"
import PropTypes from "prop-types"

export default class HTML extends React.Component {
  componentDidMount() {
    console.log('hello world');
  }
  render() {
    return (
      <html {...this.props.htmlAttributes}>
        <head>
          <meta charSet="utf-8" />
          <meta httpEquiv="x-ua-compatible" content="ie=edge" />
          <meta
            name="viewport"
            content="width=device-width, initial-scale=1, shrink-to-fit=no"
          />
          {this.props.headComponents}
        </head>
        <body>
          {this.props.preBodyComponents}
          <div
            key={`body`}
            id="___gatsby"
            dangerouslySetInnerHTML={{ __html: this.props.body }}
          />
          {this.props.postBodyComponents}
        </body>
      </html>
    )
  }
}

HTML.propTypes = {
  htmlAttributes: PropTypes.object,
  headComponents: PropTypes.array,
  bodyAttributes: PropTypes.object,
  preBodyComponents: PropTypes.array,
  body: PropTypes.string,
  postBodyComponents: PropTypes.array,
}

As you can see i replaced the componentDidMount() method to write out to the console and it didn't there's something preventing this method from executing.

If anyone has experience with this please do share, thanks.


If you want to add jQuery as an external (load from CDN) to gastby, it's a bit tricky. You'd need to:

  • add jquery CDN to html.js
  • add external to webpack config in gatsby-node.js

Add jQuery to html.js

⚠️ Edit: This should be done via gatsby-ssr, please refer @rosszember answer for context..

You've probably already done this: cp .cache/default-html.js src/html.js, and add

// src/html.js
<head>
  <script
    src="https://code.jquery.com/jquery-3.3.1.min.js"
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossOrigin="anonymous"
  />
</head>

But there's a caveat: it's crossOrigin, not crossorigin. At this point, if you use $ even in componentDidMount, it'd still throw error, as webpack doesn't know about jquery.

Add external to webpack config in gatsby-node.js

We need to inform webpack about jQuery.

//gatsby-node.js
exports.onCreateWebpackConfig = ({
  actions,
}) => {
  const { setWebpackConfig } = actions;
  setWebpackConfig({
    externals: {
      jquery: 'jQuery', // important: 'Q' capitalized
    }
  })
}

Usage

Now, in componentDidMount you can do

import $ from 'jquery' // important: case sensitive.

componentDidMount() {
  $('h1').css('color', 'red');
}

Why case sensitive

When we set external: { X: Y } We're essentially telling webpack that 'wherever I do import X', look for the Y in the global scope. In our case, webpack'll look for jQuery in window. jQuery attachs itself to window with 2 names: jQuery and $. This is why the capitalized Q is important.

Also, to illustrate, you can also do: external: { foo: jQuery } and use it like import $ from foo. It should still work.

Hope that helps!


Another way to add jQuery to your Gatsby project - using gatsby-ssr.js and gatsby-browser.js:

Add jQuery to gatsby-ssr.js

You need to create a gatsby-ssr.js to your root if you didn't have one already.

const React = require("react")

export const onRenderBody = ({ setHeadComponents }, pluginOptions) => {
  setHeadComponents([
    <script
      src="https://code.jquery.com/jquery-3.4.1.min.js"
      integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
      crossOrigin="anonymous">
    </script>,
  ])
}

It will put your script tag to the top of the Note: If you're running a development environment you need to run it again to make gatsby-ssr.js work

Add your code to gatsby-browser.js

You need to create a gatsby-browser.js to your root if you didn't have one already. This will be the place for your codes:

const $ = require("jquery")

export const onInitialClientRender = () => {
  $(document).ready(function () {
    console.log("The answer is don't think about it!")
  });
}

This method puts your code into the common.js You can use other APIs as well to run your code: Gatsby Browser API doc

Disclaimer

It's a little bit hacky and in general, it is not really recommended to use jQuery with Gatsby but for quick fixes, it works just fine.

Moreover, html.js is not recommended by the Gatsby guides:

Customizing html.js is a workaround solution for when the use of the appropriate APIs is not available in gatsby-ssr.js. Consider using onRenderBody or onPreRenderHTML instead of the method above. As a further consideration, customizing html.js is not supported within a Gatsby Theme. Use the API methods mentioned instead.