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 Capture Screenshots with Puppeteer In NodeJS

How to Capture Screenshots with Puppeteer In NodeJS

To Capture Screenshots with Puppeteer: Launch a Browser Instance Navigate to the Web Page Capture the Screenshot Introduction: Puppeteer is a powerful Node.js library that allows developers…

How to Minimize Puppeteer Browser Window To Tray

How to Minimize Puppeteer Browser Window To Tray

Puppeteer is a powerful tool for automating tasks in headless or non-headless web browsers using JavaScript. While Puppeteer is often used to perform actions within a browser,…

Intercepting Responses in Node.js with Puppeteer

Intercepting Responses in Node.js with Puppeteer

Introduction: Puppeteer is a powerful Node.js library that provides a high-level API for controlling headless Chrome or Chromium browsers. It’s widely used for web scraping, automated testing,…

Mastering React Component Re-rendering in Jest

Mastering React Component Re-rendering in Jest

In this hands-on guide, we’ll explore the art of optimizing React component re-rendering within Jest tests. By combining theory with practical coding examples, you’ll gain a deep…

Eliminating Nesting Loops in React Rendering

Eliminating Nesting Loops in React Rendering

React has ushered in a new era of web application development with its component-based structure, promoting code reusability and maintainability. But as projects evolve, achieving optimal performance…

Exploring Type and Interface Usage in TypeScript

Exploring Type and Interface Usage in TypeScript

TypeScript has gained immense popularity by bridging the gap between dynamic JavaScript and static typing. Two of its fundamental features, “Type” and “Interface,” play pivotal roles in…

Leave a Reply

%d bloggers like this: