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.
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.
Method 1
Placed the entire code inside of onInitialClientRender
in gatsby-browser.js
Method 2
Copied html.js
in the src
folder and added the file via the script
tag.
Method 3
Followed this answer and placed the entire code inside of
<script dangerouslySetInnerHTML= {{ __html: `putYourSciptHereInBackticks `}} />
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.
UPDATE
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.