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); }
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); } }, []);
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); });
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:
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!