Gatsby: How to include .js(local javascript) files globally ??

Created on 10 Feb 2020  路  3Comments  路  Source: gatsbyjs/gatsby

i'm converting static HTML template into Gatsby project. i'am inlude global css file in gatsby-browser.js file but i'am not sure where i include globally javascript (like main.js) files.
i have 4 to 5 .js files

Screenshot from 2020-02-11 00-12-49

My mian.js like this

`$(function(){

// -------start desctop dropdown menu--------
if(window.innerWidth > 992) {

$('.header__menu ul li').hover(function () {
  $('.dropdown-menu-wrapper',this).css('display', 'block');
}, function () { 
  $('.dropdown-menu-wrapper',this).css('display', 'none'); 
});

}

// ----------end desctop dropdown menu---------

// -------start mobil dropdown menu--------
if(window.innerWidth < 992) {
$('.header__menu ul li').click(function(){
$(this).toggleClass('active');
});
$('.header__menu--left .menu__item-drop-down').click(function(){
$('.header__menu--right').toggleClass('active');
});
}});`

question or discussion

All 3 comments

It's not advised to mix jQuery and react - generally better to convert jQuery code to react code.

That said - you can use jQuery, just make sure to not init things on "document.ready" event (in this block that usually everything is thrown into:

$(function(){
})

and instead init things in gatsby-browser.js in onRouteUpdate hook (this will make sure things will get initialized when you navigate to new page):

For example:

const $ = require(`jquery`)
window.jQuery = $
require(`@fancyapps/fancybox`)
require(`@fancyapps/fancybox/dist/jquery.fancybox.css`)

exports.onRouteUpdate = () => {
  // init things here
  $(".fancybox").fancybox()
}

But please, consider porting everything to react instead of trying to make jQuery work in Gatsby - it will work, but it will introduce problems:

  • Users of your site will have to download and evaluate twice as much of javascript (react + react-dom that gatsby normally uses + jQuery seperately)
  • jquery and react are using 2 different paradigms, so anything more complex than example I showed will be hard to reason about and might introduce weird bugs

Thank you for opening this, @KamranMaqbool

We're marking this issue as answered and closing it for now but please feel free to reopen this and comment if you would like to continue this discussion. We hope we managed to help and thank you for using Gatsby! 馃挏

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mikestopcontinues picture mikestopcontinues  路  3Comments

brandonmp picture brandonmp  路  3Comments

totsteps picture totsteps  路  3Comments

theduke picture theduke  路  3Comments

KyleAMathews picture KyleAMathews  路  3Comments