7

How To Dynamically load a JavaScript file in React

 1 year ago
source link: https://www.js-howto.com/how-to-dynamically-load-a-javascript-file-in-react/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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.

Like this:

Loading...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK