What is react-async-script?
The react-async-script npm package allows you to load external scripts asynchronously in your React applications. This can be particularly useful for integrating third-party libraries or services that require script loading, such as Google Maps, payment gateways, or analytics tools.
What are react-async-script's main functionalities?
Load External Scripts
This feature allows you to load an external script asynchronously and handle the script's loading state within your React component. The example demonstrates how to use the asyncScriptLoader HOC to load a script and check its loading status.
import React from 'react';
import asyncScriptLoader from 'react-async-script';
class MyComponent extends React.Component {
componentDidMount() {
if (this.props.isScriptLoaded && this.props.isScriptLoadSucceed) {
// Script loaded successfully
console.log('Script loaded successfully');
} else if (this.props.isScriptLoaded && !this.props.isScriptLoadSucceed) {
// Script failed to load
console.error('Script failed to load');
}
}
render() {
return <div>My Component</div>;
}
}
export default asyncScriptLoader('https://example.com/external-script.js')(MyComponent);
Handle Script Load Success and Failure
This feature allows you to handle the success and failure of script loading within the componentDidUpdate lifecycle method. The example shows how to check the script's loading status and handle it accordingly.
import React from 'react';
import asyncScriptLoader from 'react-async-script';
class MyComponent extends React.Component {
componentDidUpdate(prevProps) {
if (prevProps.isScriptLoaded !== this.props.isScriptLoaded) {
if (this.props.isScriptLoaded && this.props.isScriptLoadSucceed) {
// Script loaded successfully
console.log('Script loaded successfully');
} else if (this.props.isScriptLoaded && !this.props.isScriptLoadSucceed) {
// Script failed to load
console.error('Script failed to load');
}
}
}
render() {
return <div>My Component</div>;
}
}
export default asyncScriptLoader('https://example.com/external-script.js')(MyComponent);
Other packages similar to react-async-script
react-load-script
The react-load-script package provides a React component for loading external scripts. It offers similar functionality to react-async-script but uses a component-based approach instead of a higher-order component (HOC). This can be more intuitive for developers who prefer using components over HOCs.
react-helmet
The react-helmet package allows you to manage changes to the document head, including loading external scripts. While it is more general-purpose and not specifically focused on script loading, it provides a flexible way to include external scripts along with other head elements like meta tags and title.
React Async Script Loader
A React HOC for loading 3rd party scripts asynchronously. This HOC allows you to wrap a component that needs 3rd party resources, like reCAPTCHA or Google Maps, and have them load the script asynchronously.
Usage
Async Script HOC api
makeAsyncScriptLoader(getScriptUrl, options)(Component)
Component
: The Component to wrap.getScriptUrl
: string or function that returns the full URL of the script tag.options
(optional):
callbackName
: string : If the script needs to call a global function when finished loading (for example: recaptcha/api.js?onload=callbackName
). Please provide the callback name here and it will be autoregistered on window
for you.globalName
: string : Can provide the name of the global that the script attaches to window
. Async-script will pass this as a prop to the wrapped component. (props[globalName] = window[globalName]
)removeOnUnmount
: boolean default=false : If set to true
removes the script tag when component unmounts.
HOC Component props
const AsyncScriptComponent = makeAsyncScriptLoader(URL)(Component);
---
<AsyncScriptComponent asyncScriptOnLoad={callAfterScriptLoads} />
asyncScriptOnLoad
: function : called after script finishes loading. using script.onload
Ref and forwardRef
react-async-script
uses react's forwardRef
method to pass along the ref
applied to the wrapped component.
If you pass a ref
prop you'll have access to your wrapped components instance. See the tests for detailed example.
Simple Example:
const AsyncHoc = makeAsyncScriptLoader(URL)(ComponentNeedsScript);
class DisplayComponent extends React.Component {
constructor(props) {
super(props);
this._internalRef = React.createRef();
}
componentDidMount() {
console.log("ComponentNeedsScript's Instance -", this._internalRef.current);
}
render() { return (<AsyncHoc ref={this._internalRef} />)}
}
Notes on Requirements
At least React@16.4.1
is required due to forwardRef
usage internally.
Example
See https://github.com/dozoisch/react-google-recaptcha
export class ReCAPTCHA extends React.Component {
componentDidUpdate(prevProps) {
if (!prevProps.grecaptcha && this.props.grecaptcha) {
this.props.grecaptcha.render(this._container)
}
}
render() { return (
<div ref={(r) => this._container = r} />)
}
}
import makeAsyncScriptLoader from "react-async-script";
import { ReCAPTCHA } from "./recaptcha";
const callbackName = "onloadcallback";
const URL = `https://www.google.com/recaptcha/api.js?onload=${callbackName}&render=explicit`;
const globalName = "grecaptcha";
export default makeAsyncScriptLoader(URL, {
callbackName: callbackName,
globalName: globalName,
})(ReCAPTCHA);
import ReCAPTCHAWrapper from "./recaptcha-wrapper.js"
const onLoad = () => console.log("script loaded")
React.render(
<ReCAPTCHAWrapper asyncScriptOnLoad={onLoad} />,
document.body
);
Notes
Pre 1.0.0
and - React < 15.5.*
support details in 0.11.1.