Ferdy
Ferdy

Reputation: 678

Storing JS variable before react js loaded

We have Rails app with react as front-end framework .. I need to store some hash value in javascript variable like

windows.FeatureFlag = {featureA: true, featureB:false}

before all files are loading... we are loading the js file in the following order

//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require react-server
//= require react_ujs
//= require_tree .

I'm trying to set the above FeatureFlag before the react js loaded... I have tried adding DOMContentLoaded but still, the variable defined as undefined..

I react file we require/set multiple different values and all are depending on this variable to avoid multiple server calls...

how to achieve?

Upvotes: 1

Views: 71

Answers (2)

penner
penner

Reputation: 2737

Jared's answer would work but it adds another request for the client, doesn't get preprocessed, needs to be included in all the layouts. I would:

Create a new file for the script... call it react_config.js

windows.FeatureFlag = {featureA: true, featureB:false}

then:

//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require react_config.js
//= require react-server
//= require react_ujs
//= require_tree .

application.js is already included in the

Upvotes: 1

Jared Beck
Jared Beck

Reputation: 17528

Put it at the top of the document <head>

<head>
  <script>
    window.featureFlags = {featureA: true, featureB:false};
  </script>
  <!-- now load everything else -->
</head>

Usually, the <head> is in app/views/layouts/application.

You may also find content_for useful.

Upvotes: 0

Related Questions