Closed SiddharthaSauravGogoi closed 6 years ago
Generally you wrap your code in onReady
which handles this http://learn.jquery.com/using-jquery-core/document-ready/
Also you can put jquery in a js module and import it into your gatsby-browser.js and run your code in either https://www.gatsbyjs.org/docs/browser-apis/#onInitialClientRender if you only need to run it when the page loads or https://www.gatsbyjs.org/docs/browser-apis/#onRouteUpdate where it'll be run after every page renders.
Another way is to use the React useEffect (for functional component) or componentDidMount (for class component).
The idea is simple, after the component is completely rendered, we will append an additional <script>
tag object at its end
import React, { useEffect } from 'react'
const MyComponent = () => {
useEffect(() => {
const mainJsTag = document.createElement('script')
// given the js/main.js file is put in the static folder
mainJsTag.src = 'assets/js/main.js'
document.body.appendChild(mainJsTag)
console.log('Component Rendered!')
});
return (
<main>
<text>Pretty much the component's body code around here</text>
</main>
)
}
export default MyComponent
Summary
I have a project that has several
js
andjQuery
files that need to be loaded after the body has rendered(in simple html + css way). Script and meta tags are included in the project with the help ofReact Helmet
.Basically what
React Helmet
does is pushes all these code inside the head of the document. In other words thejs
+jQuery
files are loaded before the DOM(VirtualDOM) is rendered. Doesn't that effect the manipulation jQuery is supposed to do?Is there a solution for this problem?
Relevant information
Environment (if relevant)
Windows 7 64 bit
File contents (if changed)
package.json
:gatsby-node.js
: N/Agatsby-browser.js
: N/Agatsby-ssr.js
: N/A