0

I am trying to include a script tag with some code inside based on an environment variable on a react project.

Let's say that I want the following code to load if the certain env variable is matched.

<script type="text/javascript">

var something = function() {
 // some code
}

something()

</script>

I can access the value of evn variable in the HTML file so I could create a script tag using document.createElement('script') dynamically based on the value but that way I am only able to create a script tag but not content inside the script tag. Is there any way I can create the script tag and also insert some code inside that script tag?

I basically want to load the script tag above including the code inside on domcontentloaded event.

3
  • Why can't you just execute the code inside the script tag within React? Commented Aug 6, 2019 at 20:49
  • 1
    You can import your script instead of creating DOM element with script. See import Commented Aug 6, 2019 at 20:51
  • You can create content inside the result of document.createElement('script') by setting its textContent property... Commented Aug 6, 2019 at 20:52

2 Answers 2

1

Here is one way:

 <script type="text/javascript">
 if(navigator.appName == 'Microsoft Internet Explorer') {
    document.write("<script tag here>");
 } else {
 document.write("<other script tag here>");
 }
</script>

Another way is to define whatever source is and assign attributes dynamically using JS:

// Create 2 .JS files and apply whatever conditional logic here to 
set the src attribute
var src = navigator.appName == "Load one.js" ? 

"one.js" : "two.js";

var script = document.createElement("script");
script.setAttribute("src", src);
document.getElementsByTagName("head")[0].appendChild(script);

And finally, if you're already using JQuery in your project you can use $.getScript() to load a JS file from the server using GET: https://api.jquery.com/jQuery.getScript/

Sign up to request clarification or add additional context in comments.

Comments

1

Its support ejs there although. add this in head tag, it works-

<% if (process.env.NODE_ENV === 'production') { %>
  <script>
    // my GA script
  </script>
<% } %>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.