在gatsby中包含.js文件的正确方法,该文件将在所有页面上执行其代码 [英] Proper way to include a .js file in gatsby which executes its code on all the pages
问题描述
前提
我有一个静态网站,正在将其转换为 gatsby 一个.我使用jQuery进行了某些DOM操作和其他触发器,例如切换移动菜单和处理cookie.我想以这种方式包含 main.js
这个文件,以使其中的JavaScript在所有页面上都得以执行.
Premise
I have a static site which I'm converting into a gatsby one. I've used jQuery to do certain DOM manipulation and other triggers like toggling the mobile menu and handling cookies. I want to include this file, main.js
in such a way that the JavaScript inside of it gets executed on all the pages.
我已经使用npm安装了jQuery,并使用 layout.js
中从"jquery"导入$
I've installed jQuery using npm and included it in layout.js
using
import $ from "jquery"
我无法以可靠的方式实现上述目标.以下是我尝试未成功的方法.
I'm not able to achieve the above in a reliable way. Following are the methods that I've tried without any success.
方法1
将整个代码放在 gatsby-browser.js
方法2
在 src
文件夹中复制 html.js
,并通过 script
标记添加文件.
Method 2
Copied html.js
in the src
folder and added the file via the script
tag.
方法3
遵循此答案,并将整个代码放在
Method 3
Followed this answer and placed the entire code inside of
<script dangerouslySetInnerHTML= {{ __html: `putYourSciptHereInBackticks `}} />
方法4
遵循此答案,并尝试使用 react-helmet
包含文件.该代码确实使用此方法执行,但仅在网站加载时执行.如果我遍历其他页面,即使返回同一页面也不会.
Method 4
Followed this answer and tried to include the file using react-helmet
. The code does execute using this method but only when the site is loaded. If I traverse to other pages, it doesn't, even when I come back to the same page.
现在,通过保持方法4并从 gatsby-browser.js
中下的
像这样: main.js
中复制整个代码,它可以正常工作onRouteUpdate
For now, I've got it working by keeping the method 4 and copying the entire code from main.js
in gatsby-browser.js
under onRouteUpdate
like so:
const $ = require("jquery");
exports.onRouteUpdate = () => {
$(document).ready(function(){
// Code
});
}
但是,我知道这是多余的,而且绝对不是正确的处理方式.
However, I know this is redundant and definitely not the correct way of doing things.
推荐答案
gatsby-browser.js
提供了最好,最干净的解决方案.您可以尝试以下方法:
The best and cleanest solution is provided by gatsby-browser.js
. You could try something like:
import yourScript from '../../your/script/path/file.js'
export const onClientEntry= () => yourScript();
您可以在 Gatsby Browswer API文档中看到,Gatsby提供了几种可用的方法以及合适的API来触发(几乎)任何所需的用例.最适合您的要求的是 onClientEntry
.根据文档:
As you can see in Gatsby Browswer APIs documentation, Gatsby offers several available and suitable APIs to trigger in (almost) any desired use-case. The one that fits your requirements best is onClientEntry
. According to the documentation:
(_:emptyArg,pluginOptions:pluginOptions)=>未定义
在Gatsby浏览器运行时首次启动时调用.
Called when the Gatsby browser runtime first starts.
该脚本将在第一个渲染时触发,并且在使用锚点而不是使用 @ reach/router
(< Link>
和 navigate
).
The script will be triggered on the first render and when navigating through pages using anchors, not using @reach/router
(<Link>
and navigate
).
这篇关于在gatsby中包含.js文件的正确方法,该文件将在所有页面上执行其代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!