@shopify/hydrogen-react
Version:
React components, hooks, and utilities for creating custom Shopify storefronts
54 lines (53 loc) • 1.59 kB
JavaScript
;
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const React = require("react");
const SCRIPTS_LOADED = {};
function loadScript(src, options) {
const isScriptLoaded = SCRIPTS_LOADED[src];
if (isScriptLoaded) {
return isScriptLoaded;
}
const promise = new Promise((resolve, reject) => {
const script = document.createElement("script");
if (options == null ? void 0 : options.module) {
script.type = "module";
} else {
script.type = "text/javascript";
}
script.src = src;
script.onload = () => {
resolve(true);
};
script.onerror = () => {
reject(false);
};
if ((options == null ? void 0 : options.in) === "head") {
document.head.appendChild(script);
} else {
document.body.appendChild(script);
}
const attributes = options == null ? void 0 : options.attributes;
if (attributes) {
Object.keys(attributes).forEach((key) => {
script.setAttribute(key, attributes[key]);
});
}
});
SCRIPTS_LOADED[src] = promise;
return promise;
}
function useLoadScript(url, options) {
const [status, setStatus] = React.useState("loading");
React.useEffect(
() => {
loadScript(url, options).then(() => setStatus("done")).catch(() => setStatus("error"));
},
// Ignore options changes since it won't trigger a new load.
// eslint-disable-next-line react-hooks/exhaustive-deps
[url]
);
return status;
}
exports.loadScript = loadScript;
exports.useLoadScript = useLoadScript;
//# sourceMappingURL=load-script.js.map