Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
makeAsyncScriptLoader
✓ import makeAsyncScriptLoader from 'react-async-script';
✗ import { makeAsyncScriptLoader } from 'react-async-script'; // Incorrectly attempts named import for a default export
The `makeAsyncScriptLoader` HOC is exported as the default export in modern (ESM) environments. Using named import syntax will result in an `undefined` value.
makeAsyncScriptLoader (CommonJS)
✓ const makeAsyncScriptLoader = require('react-async-script');
✗ const { makeAsyncScriptLoader } = require('react-async-script'); // Incorrectly destructures a default export in CommonJS
For CommonJS environments (e.g., Node.js or older bundlers), the `require` statement directly retrieves the default export. Destructuring it will lead to an `undefined` value or a runtime error.
Demonstrates how to use `makeAsyncScriptLoader` to load an external script (e.g., Google Maps API), handle its `onload` callback, access global variables exposed by the script, and utilize `forwardRef` with the wrapped component. Replace `YOUR_API_KEY` with an actual key.
import React from 'react';
import ReactDOM from 'react-dom';
import makeAsyncScriptLoader from 'react-async-script';
// A placeholder component that would typically consume the loaded script
class MyComponentNeedingScript extends React.Component {
componentDidUpdate(prevProps) {
// Access the global object exposed by the loaded script via props
if (!prevProps.googleMaps && this.props.googleMaps) {
console.log('Google Maps API is available:', this.props.googleMaps);
// Example: Initialize a map once the API is loaded
// new this.props.googleMaps.Map(document.getElementById('map'), { center: {lat: -34, lng: 151}, zoom: 8 });
}
}
render() {
return (
<div>
<p>Loading external script...</p>
{/* You might render a placeholder or a loading spinner here */}
<div id="map" style={{ width: '100%', height: '300px' }}></div>
</div>
);
}
}
// Define the script URL, callback name, and the global object name
const SCRIPT_URL = `https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap`;
const CALLBACK_NAME = 'initMap';
const GLOBAL_NAME = 'googleMaps'; // The global object set by the script (e.g., window.googleMaps)
// Wrap your component with the HOC
const GoogleMapsLoader = makeAsyncScriptLoader(SCRIPT_URL, {
callbackName: CALLBACK_NAME,
globalName: GLOBAL_NAME,
removeOnUnmount: true, // Optional: remove script tag when component unmounts
})(MyComponentNeedingScript);
class App extends React.Component {
constructor(props) {
super(props);
this._myRef = React.createRef();
}
componentDidMount() {
console.log("Ref to MyComponentNeedingScript instance:", this._myRef.current);
}
handleScriptLoad = () => {
console.log("External Google Maps script has finished loading!");
// Any post-load actions can be performed here
};
render() {
return (
<div>
<h1>React Async Script Loader with Google Maps</h1>
<GoogleMapsLoader ref={this._myRef} asyncScriptOnLoad={this.handleScriptLoad} />
</div>
);
}
}
// Ensure a root element exists for React to render into
const rootElement = document.getElementById('root');
if (!rootElement) {
const div = document.createElement('div');
div.id = 'root';
document.body.appendChild(div);
}
ReactDOM.render(<App />, rootElement);
// Simulate the global callback function that the Google Maps API calls
// This must be a global function for the script to find it
window[CALLBACK_NAME] = () => {
console.log(`Global callback '${CALLBACK_NAME}' executed.`);
// For Google Maps, the 'google.maps' global becomes available after this.
// The HOC will pick this up and pass 'googleMaps' as a prop.
};
Errors
Common errors & fixes
TypeError: (0, react_async_script__WEBPACK_IMPORTED_MODULE_0__.makeAsyncScriptLoader) is not a function
Attempting to import `makeAsyncScriptLoader` as a named export from `react-async-script` in an ESM context, but it is a default export.
fixChange your import statement from `import { makeAsyncScriptLoader } from 'react-async-script';` to `import makeAsyncScriptLoader from 'react-async-script';`. Error: Invariant Violation: The `ref` prop is only available for DOM components or using React.forwardRef(). Check the render method of `YourWrappedComponent`.
This error typically indicates an incompatibility with the React version being used, as `react-async-script` relies on `forwardRef` introduced in React 16.4.1, or an issue with how `ref` is being handled in your own components if you're attempting to forward it further.
fixVerify that your `react` and `react-dom` packages are at least version `16.4.1`. If you are trying to attach a `ref` to your own functional component that is then wrapped by the HOC, ensure that component itself uses `React.forwardRef`.
Audit
Dependencies
reactrequiredPeer dependency for React component usage, specifically for `React.forwardRef` functionality.