我在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,
},
},
答案 0 :(得分:0)
您应该看看gatsby-plugin-snipcartv3。我相信gatsby-plugin-snipcart已被弃用,无法与Snipcart v3一起使用。
但是据我所知,还没有办法告诉插件仅在特定页面上加载脚本。
答案 1 :(得分:0)
您可以直接使用Snipcart,而不使用插件来对其进行更多控制。
假设您有一个layout.js
文件,用于包装页面内容,您可以有一个loadSnipcart
标志,仅在需要时才加载Snipcart文件。
这是一个例子:
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>
)
}
import React from "react"
import Layout from "./layout"
export default () => {
return (
<Layout loadSnipcart>
<h1>Welcome to my shop !</h1>
</Layout>
)
}
import React from "react"
import Layout from "./layout"
export default () => {
return (
<Layout>
<h1>This page doesn't load Snipcart</h1>
</Layout>
)
}