How to dynamically load javascript file in react.js?

by scotty_walker , in category: Javascript , 5 months ago

How to dynamically load javascript file in react.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 5 months ago

@scotty_walker 

To dynamically load a JavaScript file in React.js, you can use the <script> tag with the src attribute. Here's an example of how you can do it:

  1. Create a component that will handle the dynamic loading of the JavaScript file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import React, { useEffect } from 'react';

function DynamicScriptLoader({ scriptUrls }) {
  useEffect(() => {
    // Function to load the script dynamically
    const loadScript = (url) => {
      return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = url;
        script.async = true;
        script.onload = resolve;
        script.onerror = reject;
        document.body.appendChild(script);
      });
    };

    // Load all the specified script URLs
    Promise.all(scriptUrls.map(loadScript))
      .then(() => {
        console.log('Scripts loaded successfully!');
      })
      .catch(() => {
        console.error('Error occurred while loading scripts.');
      });
  }, [scriptUrls]);

  return <div>DynamicScriptLoader</div>;
}

export default DynamicScriptLoader;


  1. Use the DynamicScriptLoader component in your app and pass an array of script URLs as its prop:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import React from 'react';
import DynamicScriptLoader from './DynamicScriptLoader';

function App() {
  const scriptUrls = [
    'https://example.com/script1.js',
    'https://example.com/script2.js',
    // Add more script URLs here...
  ];

  return (
    <div>
      <h1>Hello, React.js!</h1>
      <DynamicScriptLoader scriptUrls={scriptUrls} />
    </div>
  );
}

export default App;


In the example above, the DynamicScriptLoader component takes an array of script URLs as its prop. It uses the useEffect hook to load the scripts dynamically when the component is mounted. Once all the scripts are loaded, the then block will be executed. If any error occurs during script loading, the catch block will handle it.


Make sure to replace 'https://example.com/script1.js' and 'https://example.com/script2.js' with actual URLs of the JavaScript files you want to load dynamically in your app.