Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to include a .js file in gatsby which executes its code on all the pages

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.

like image 905
nimsrules Avatar asked Aug 13 '19 05:08

nimsrules


1 Answers

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();

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) => undefined

Called when the Gatsby browser runtime first starts.

The script will be triggered on the first render and when navigating through pages using anchors, not using @reach/router (<Link> and navigate).

like image 147
Ferran Buireu Avatar answered Sep 26 '22 06:09

Ferran Buireu