3

我在 Gatsby 中使用 Snipcart 插件,但脚本会随处加载。是否可以通过某种功能仅在 1 个特定页面上触发脚本,而不是完全触发?

以下是我在 Gatsby-config.js 文件中使用的选项

{
      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,
      },
    },
4

2 回答 2

0

你应该看看gatsby-plugin-snipcartv3。我相信 gatsby-plugin-snipcart 已被弃用,并且不适用于 Snipcart v3。

但据我所知,没有办法告诉插件仅在特定页面上加载脚本。

于 2020-02-26T15:26:06.503 回答
0

您可以直接使用 Snipcart,而不是使用插件,来对其进行更多控制。

假设您有一个layout.js文件,为您的页面包装内容,您可以有一个loadSnipcart标志,仅在您需要时加载 Snipcart 文件。

这是一个例子:

布局.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>
    )
}
于 2020-06-04T10:00:16.760 回答