Home > Web Front-end > JS Tutorial > How to Dynamically Add Script Tags in React?

How to Dynamically Add Script Tags in React?

Mary-Kate Olsen
Release: 2024-12-14 07:55:10
Original
237 people have browsed it

How to Dynamically Add Script Tags in React?

Adding Script Tag to React/JSX

For dynamic script loading, there are a few approaches to consider:

Option 1: Using the componentDidMount Lifecycle Method

For scripts that need to be executed only once when the component mounts, you can utilize the componentDidMount method:

componentDidMount() {
    const script = document.createElement("script");

    script.src = "https://use.typekit.net/foobar.js";
    script.async = true;

    document.body.appendChild(script);
}
Copy after login

Option 2: Using useEffect Hook

With the advent of hooks in React, useEffect offers a more concise and reusable solution:

useEffect(() => {
  const script = document.createElement('script');

  script.src = "https://use.typekit.net/foobar.js";
  script.async = true;

  document.body.appendChild(script);

  return () => {
    document.body.removeChild(script);
  }
}, []);
Copy after login

Option 3: Fetching and Executing Script Dynamically

If the script needs to be fetched and executed multiple times, a more dynamic approach is required:

fetch('https://use.typekit.net/foobar.js')
  .then(res => res.text())
  .then(scriptText => {
    const script = document.createElement('script');

    script.text = scriptText;

    document.body.appendChild(script);
  });
Copy after login

Consider Module/Package Approach

However, before resorting to dynamic script loading, it's always advisable to first verify if the required script is available as a module or package via npm. This approach offers several benefits:

  • Code can be imported cleanly
  • Package updates can be easily managed
  • Potential to leverage built-in error handling mechanisms

The above is the detailed content of How to Dynamically Add Script Tags in React?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template