【问题标题】:Only load Snipcart on specific page in Gatsby仅在 Gatsby 的特定页面上加载 Snipcart
【发布时间】:2020-02-25 14:00:06
【问题描述】:

我在 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,
      },
    },

【问题讨论】:

    标签: reactjs gatsby jamstack snipcart


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      这是一个例子:

      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>
          )
      }
      

      【讨论】:

        猜你喜欢
        • 2021-01-21
        • 2011-07-16
        • 1970-01-01
        • 1970-01-01
        • 2021-09-22
        • 1970-01-01
        • 1970-01-01
        • 2020-05-15
        • 2013-10-21
        相关资源
        最近更新 更多