Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-async-script

dozoisch3.4mMIT1.2.0TypeScript support: definitely-typed

A composition mixin for loading scripts asynchronously for React

react, asynchronous, script-loader

readme

React Async Script Loader

Build Status npm version npm downloads Dependencies

*NOTE - These are the docs for the upcoming 1.0.0 release - for v0.11.1 documention go to tag here: 0.11.1

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):
    • attributes: object : If the script needs attributes (such as data- attributes), then provide them as key/value pairs of strings and they will be added to the generated script tag.
    • 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.
    • scriptId: string : If set, it adds the following id on the script tag.

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.1is required due toforwardRef` usage internally.

Example

See https://github.com/dozoisch/react-google-recaptcha

// recaptcha.js
export class ReCAPTCHA extends React.Component {
  componentDidUpdate(prevProps) {
    // recaptcha has loaded via async script
    if (!prevProps.grecaptcha && this.props.grecaptcha) {
      this.props.grecaptcha.render(this._container)
    }
  }
  render() { return (
    <div ref={(r) => this._container = r} />)
  }
}

// recaptcha-wrapper.js
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`;
// the name of the global that recaptcha/api.js sets on window ie: window.grecaptcha
const globalName = "grecaptcha";

export default makeAsyncScriptLoader(URL, {
  callbackName: callbackName,
  globalName: globalName,
})(ReCAPTCHA);

// main.js
import ReCAPTCHAWrapper from "./recaptcha-wrapper.js"

const onLoad = () => console.log("script loaded")

React.render(
  <ReCAPTCHAWrapper asyncScriptOnLoad={onLoad} />,
  document.body
);

Migration to 1.0

  • Component is now passed as a second function call
  • removeOnMount is now removeOnUnmount (typo fixed!)
  • exposeFuncs is no longer needed as it's done automatically!
-export default makeAsyncScriptLoader(ReCAPTCHA, getURL, {
+export default makeAsyncScriptLoader(getURL, {
   callbackName,
   globalName,
-  removeOnMount: initialOptions.removeOnMount || false,
+  removeOnUnmount: initialOptions.removeOnUnmount || false,
-  exposeFuncs: ["getValue", "getWidgetId", "reset", "execute"],
-});
+})(ReCAPTCHA);

Notes

Pre 1.0.0 and - React < React@16.4.1 support details in 0.11.1.


changelog

v1.2.0 - Mon Jun 22 2020 15:36:00 PST

  • Added support for optional attributes that can be added to the generated script tag (#52)
  • Update various dependencies (notably babel/react) (#48)

v1.1.1 - Sun Jul 14 2019 11:14:00 PST

  • Add node 12 to build (#46)

v1.1.0 - Sun Jul 14 2019 10:19:00 PST

  • Switch to Jest (#45)
  • Upgrade dependencies and add es module (#44)

v1.0.1 - Sun 17 Apr 2019 19:14:00 PST

  • Support for adding a script id attribute (#43)

v1.0.0 - Fri 17 Aug 2018 17:32:00 PST

  • React forward ref (#37)
  • Update to react 16.4.1 (#37)
  • Hoist non react statics (#35)
  • Updated Travis Node versions (#36)
  • Refactor to new HOC pattern (#34)
  • Remove old broken IE support (#34)
  • Add migration notes (#40)

v0.11.1 - Sat, 4 Aug 2018 12:46:00 PST

  • Remove babel-runtime peer dep (#32)
  • Readme updates (#31)

v0.11.0 - Sun, 29 Jul 2018 11:58:00 PST

  • Remove transform runtime (#29)
  • Added dynamic url capability (#30)

v0.10.0 - Tue, 24 Jul 2018 14:40:00 PST

  • Clean up use of Map to remove core-js polyfills (#27)

v0.9.1 - Wed, 19 Apr 2017 6:05:00 PST

  • Fixed issue where method was not bound properly (#19)

v0.9.0 - Sun, 16 Apr 2017 4:12:00 PST

  • Changed updated to react >=15.5 (#18)

v0.8.0 - Thu, 23 Mar 2017 5:46:00 PST

  • Added removeOnUnmount parameter (#14)

v0.7.0 - Sat, 04 Mar 2017 6:37:00 PST

  • Updated deps to react 15 and babel 6 (#13)
  • Go back to manual changelogs

v0.6.0 - Thu, 02 Jun 2016 01:18:21 GMT

v0.5.1 - Fri, 15 Jan 2016 13:21:01 GMT

  • 65d1313 [added] old history to new changelog file

v0.5.0 - Thu, 15 Oct 2015 21:10:33 GMT

  • 9059f9e [changed] travis to build only master & prs
  • 52bb6d5 [changed] updated deps
  • 4920f59 [changed] Build Tools to use babel
  • 253dbf2 [fixed] onLoad propname in readme

0.4.0

  • Fixed issue with refs
  • Bump all deps

0.3.2

  • Bump deps

0.3.1

  • Removed uncessary "use strict"
  • Bump deps

0.3.0

  • Added a way to expose child functions

0.2.2

  • Fix instanciation when global object already exists

0.2.1

  • Put runtime in deps and not dev-deps

0.2.0

  • Back to es6 Map

0.1.2

  • Added a small test
  • Added some badges
  • small fixes

0.1.1

  • reverted es6 map back to plain object

0.1.0

  • Added the composition function
  • Added build files
  • Added david-dm badge
  • Initial readme