How To Dynamically load a JavaScript file in React

Introduction

Some use cases require loading a specific Javascript script conditionally, this article will demonstrate how to dynamically load a javascript file in React once a particular condition is met.

How To Dynamically load a JavaScript file in React

Consider we have the requirement to load the script only once the user is logged in.

In this case, once we have the user details identified, we can fire the loading script functionality.

Example

import React, { useState, useEffect } from 'react';
import './style.css';

export default function App() {
  const [user, setUser] = useState(false);
  const [scriptLoadingState, setScriptLoadingState] = useState('IDLE');

  useEffect(() => {
    if (user) {
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = 'https://www.google-analytics.com/analytics.js';
      script.onload = function () {
        setScriptLoadingState('LOADED');
      };
      script.onerror = function () {
        setScriptLoadingState('FAILED');
      };
      document.body.appendChild(script);
    }
  }, [user]);

  return (
    <div>
      <button
        onClick={() => setUser(true)}
        style={{ width: '200px', height: '30px', fontSize: '16px' }}
      >
        Login
      </button>
      <h2>
        Script Loading State:{' '}
        <span
          style={{
            color:
              scriptLoadingState === 'IDLE'
                ? 'grey'
                : scriptLoadingState === 'LOADED'
                ? 'green'
                : 'red',
          }}
        >
          {scriptLoadingState}
        </span>
      </h2>
    </div>
  );
}

In the above example, we have two component state variables:

  • user: a boolean flag to simulate the user logged-in state.
  • scriptLoadingState: a string value that reflects the script loading state.

What happens next, is that once the user opens the App, the script initially won’t be loaded, until the user clicked on the Login button, which will update the user to true, then we’ve used the useEffect hook to listen for the user state change, once that happens, the useEffect hook will be executed, and the following logic will be executed:

  • An element of type script is created.
  • The script type is set to text/javascript.
  • Scrip src is set to the google analytics script.
  • Callback functions are attached to the events onload/onerror respectively, to update the scriptLoadingState variable.
  • Then, we do append the script tag into the webpage body.

Now, navigating to the browser, we can see initially the script loading state is IDLE, and there’s no request in the console Network tab issued to fetch the google analytics script, as shown below:

How To Dynamically load a JavaScript file in React
How To Dynamically load a JavaScript file in React

By clicking on the Login button, we can see the script loading state is updated to LOADED, and an HTTP request is issued to GET the google analytics script, as shown below:

How To Dynamically load a JavaScript file in React
How To Dynamically load a JavaScript file in React

Full Source Code.

That’s it! And as always happy coding.

Photo from Unsplash.

Related Posts

How to remove highcharts.com credits link

How to remove highcharts.com credits link

Highcharts is a popular JavaScript charting library that offers a wide range of interactive and customizable charts for developers. However, if you’re using the free version of…

Highcharts Place text in the center of a pie chart

Highcharts Place text in the center of a pie chart

To place text in the center of a pie chart in Highcharts, you can use the chart.renderer object to create a custom label and position it in…

Test design breakpoints using jest and react-testing-library

Test responsive design using jest and react-testing-library

Testing design breakpoints in React applications is an important aspect of front-end development. It ensures that the components look and behave as expected on different screen sizes….

Testing React-Query with Jest and React-testing-library

Testing React-Query with Jest and React-testing-library

Introduction In this article we will cover the basic usage of testing useQuery hook from tanstack/react-query library, along with how to test it using jest and react-testing-library….

Highcharts How To Change Series Color with examples

Highcharts How To Change Series Color with examples

To change the color of a series in Highcharts, there are a set of options we are going to discover in this article. Option 1: Using the…

A quick introduction to Javascript shadow DOM

A quick introduction to Javascript shadow DOM

Introduction JavaScript Shadow DOM is a powerful tool for creating isolated and reusable components in web development. It allows developers to create custom elements with their own…

Leave a Reply

%d bloggers like this: