

How To Dynamically load a JavaScript file in React
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.

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 totext/javascript
. - Scrip
src
is set to the google analytics script. - Callback functions are attached to the events
onload
/onerror
respectively, to update thescriptLoadingState
variable. - Then, we do append the
script
tag into the webpagebody
.
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
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
That’s it! And as always happy coding.
Photo from Unsplash.
Like this:
Recommend
-
12
How to load script dynamically in ReactAdding a script to the website is the common requirement. Let’s suppose that the website is using some external tools. To use it properly, you will have to use external java...
-
10
How to load a CSS file async We can load CSS asynchronously like this: <link rel="stylesheet" href="style.css" media="print" onload="this.media='all'; this.onload=null;"> When should I use...
-
9
Dynamically Importing Components with React.lazy In JavaScript frameworks like React, it's tempting to statically import a wide range of components. But not all of them are needed immediately; some components only render afte...
-
30
WIX: How to dynamically configure the name of the msi output file advertisements I want to include some dynamic part in the filename of the ms...
-
5
This article assumes you have basic knowledge on React and Redux. If you like to learn more about React or Redux, you can go here to learn more.
-
7
[JavaScript] Load Favicon Dynamically Updated: February 23, 2015 This po...
-
10
Sometimes it is useful to load JavaScript or CSS file dynamically. In
-
12
To load (external) CSS file dynamically, insert the following LoadCSS function to your JavaScript code: function LoadCSS(url) { var ext = document.createElement('link'); ext.setAttribute("type", "text/css"); ext.s...
-
11
PranavB6 ...
-
10
How to Lazy and Dynamically Load a Component in Angular There are three ways you can use a component in an Angular app. Loading on route change Using as a child component Dynamic...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK