html.js在页面加载Gatsby时只加载一次脚本



我正在使用html.js加载自定义脚本。我在静态文件夹custom.js中创建了一个js文件,但当我运行我的项目时,它在第一次加载页面时只加载一次脚本,而当我导航到其他页面时,它不会加载脚本。

我的custom.js文件

$(document).ready(function () {
console.log("in ready");
});

我的html.js文件

import React from "react";
import PropTypes from "prop-types";
import { withPrefix } from "gatsby";
export default function HTML(props) {
return (
<html {...props.htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<script
type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"
></script>
<link
href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css"
rel="stylesheet"
type="text/css"
/>
{props.headComponents}
</head>
<body {...props.bodyAttributes}>
{props.preBodyComponents}
<div
key={`body`}
id="___gatsby"
dangerouslySetInnerHTML={{ __html: props.body }}
/>
{props.postBodyComponents}
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script
type="text/javascript"
src={withPrefix("js/custom.js")}
></script>
</body>
</html>
);
}
HTML.propTypes = {
htmlAttributes: PropTypes.object,
headComponents: PropTypes.array,
bodyAttributes: PropTypes.object,
preBodyComponents: PropTypes.array,
body: PropTypes.string,
postBodyComponents: PropTypes.array,
};

我在这里做错了什么?为什么只加载一次脚本?在每个页面导航上加载custom.js脚本需要做什么?

我也尝试在<Helmet></Helmet>的布局文件中包含custom.js,但问题相同。

感谢

我做错了什么?为什么只加载一次脚本?什么我必须在每个页面导航上加载custom.js脚本?

我认为React和jQuery等老式脚本的工作方式存在误解和上下文混合。最后,Gatsby是一个基于React的应用程序。

Reacts操作虚拟DOM(vDOM(,jQuery直接指向DOM,这对性能有极高的成本影响。如果你在React的范围之外混合使用这两种方法,你可以阻止React的水合作用,这可能会破坏你的应用程序。

您可以简单地创建一个具有空依赖项的useEffect挂钩([](,一旦为所包含的每个页面加载DOM树,就会触发该挂钩。React的生命周期应该适用于您的用例,而不会过度扼杀Gatsby生成的HTML的定制。

您的custom.js文件必须导出某些内容。简单地说:

const customJS =()=> console.log("I'm ready");
export default customJS;  

然后,在任何页面上:

import React, {useEffect} from "react";
import customJS from "../path/to/custom.js";
const AnyPage =(props)=>{
useEffect(()=>{
customJS()
}, [])

return <div>Some content for AnyPage()<div>
}
export default AnyPage;

加载DOM后,每页只触发customJS()一次。

请不要将jQuery与React一起使用,这是不需要的。

最新更新