MCPcopy Create free account
hub / github.com/dozoisch/react-async-script / AsyncScriptLoader

Class AsyncScriptLoader

src/async-script-loader.js:16–187  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

14 WrappedComponent.displayName || WrappedComponent.name || "Component";
15
16 class AsyncScriptLoader extends Component {
17 constructor(props, context) {
18 super(props, context);
19 this.state = {};
20 this.__scriptURL = "";
21 }
22
23 asyncScriptLoaderGetScriptLoaderID() {
24 if (!this.__scriptLoaderID) {
25 this.__scriptLoaderID = "async-script-loader-" + idCount++;
26 }
27 return this.__scriptLoaderID;
28 }
29
30 setupScriptURL() {
31 this.__scriptURL =
32 typeof getScriptURL === "function" ? getScriptURL() : getScriptURL;
33 return this.__scriptURL;
34 }
35
36 asyncScriptLoaderHandleLoad(state) {
37 // use reacts setState callback to fire props.asyncScriptOnLoad with new state/entry
38 this.setState(
39 state,
40 () =>
41 this.props.asyncScriptOnLoad &&
42 this.props.asyncScriptOnLoad(this.state)
43 );
44 }
45
46 asyncScriptLoaderTriggerOnScriptLoaded() {
47 let mapEntry = SCRIPT_MAP[this.__scriptURL];
48 if (!mapEntry || !mapEntry.loaded) {
49 throw new Error("Script is not loaded.");
50 }
51 for (let obsKey in mapEntry.observers) {
52 mapEntry.observers[obsKey](mapEntry);
53 }
54 delete window[options.callbackName];
55 }
56
57 componentDidMount() {
58 const scriptURL = this.setupScriptURL();
59 const key = this.asyncScriptLoaderGetScriptLoaderID();
60 const { globalName, callbackName, scriptId } = options;
61
62 // check if global object already attached to window
63 if (globalName && typeof window[globalName] !== "undefined") {
64 SCRIPT_MAP[scriptURL] = { loaded: true, observers: {} };
65 }
66
67 // check if script loading already
68 if (SCRIPT_MAP[scriptURL]) {
69 let entry = SCRIPT_MAP[scriptURL];
70 // if loaded or errored then "finish"
71 if (entry && (entry.loaded || entry.errored)) {
72 this.asyncScriptLoaderHandleLoad(entry);
73 return;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…