Only load Snipcart on specific page in Gatsby

Viewed 214

I'm using Snipcart Plugin in Gatsby but the script gets loaded everywhere. Is is it possible with some sort of function to trigger the script on only 1 specific page and not entirely?

Below are the options I'm using in my Gatsby-config.js file

{
      resolve: "gatsby-plugin-snipcart",
      options: {
        apiKey: process.env.SNIPCART_API,
        autopop: true,
        js: "https://cdn.snipcart.com/themes/v3.0.8/default/snipcart.js",
        styles: "https://cdn.snipcart.com/themes/v3.0.8/default/snipcart.css",
        jquery: false,
      },
    },
2 Answers

You should take a look at gatsby-plugin-snipcartv3. I believe the gatsby-plugin-snipcart is deprecated and is not working with Snipcart v3.

But as far as I know, there's no way to tell the plugin to load the script only on specific pages.

You could use Snipcart directly, not using the plugin, to have more control over it.

Let's say you have a layout.js file, wrapping content for your page, you can have a loadSnipcart flag that will load Snipcart files only when you need them.

Here's an example:

layout.js

import React from "react"
import Helmet from "react-helmet"

export default ({ loadSnipcart, children }) => {
    const Snipcart = () => {
        if (!loadSnipcart) return null

        return (
            <Helmet>
                <script
                    src="https://cdn.snipcart.com/themes/v3.0.8/default/snipcart.js"
                    type="text/javascript"
                />
                <link
                    href="https://cdn.snipcart.com/themes/v3.0.8/default/snipcart.css"
                    rel="stylesheet"
                />
            </Helmet>
        )
    }

    return (
        <div id="main-content">
            <Snipcart />
            {children}
        </div>
    )
}

shop.js

import React from "react"
import Layout from "./layout"

export default () => {
    return (
        <Layout loadSnipcart>
            <h1>Welcome to my shop !</h1>
        </Layout>
    )
}

index.js

import React from "react"
import Layout from "./layout"

export default () => {
    return (
        <Layout>
            <h1>This page doesn't load Snipcart</h1>
        </Layout>
    )
}
Related