Skip to content

Commit

Permalink
Refactor useScript
Browse files Browse the repository at this point in the history
  • Loading branch information
tylermcginnis committed Aug 29, 2023
1 parent 78360d3 commit 3529e5c
Showing 1 changed file with 2 additions and 18 deletions.
20 changes: 2 additions & 18 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1075,9 +1075,7 @@ export function useScript(src, options = {}) {
const cachedScriptStatuses = React.useRef({});

React.useEffect(() => {
if (!src) {
return;
}
if (!src) return;

const cachedScriptStatus = cachedScriptStatuses.current[src];
if (cachedScriptStatus === "ready" || cachedScriptStatus === "error") {
Expand All @@ -1088,26 +1086,12 @@ export function useScript(src, options = {}) {
let script = document.querySelector(`script[src="${src}"]`);

if (script) {
setStatus(
script.getAttribute("data-status") ?? cachedScriptStatus ?? "loading"
);
setStatus(cachedScriptStatus ?? "loading");
} else {
script = document.createElement("script");
script.src = src;
script.async = true;
script.setAttribute("data-status", "loading");
document.body.appendChild(script);

const setAttributeFromEvent = (event) => {
const scriptStatus = event.type === "load" ? "ready" : "error";

if (script) {
script.setAttribute("data-status", scriptStatus);
}
};

script.addEventListener("load", setAttributeFromEvent);
script.addEventListener("error", setAttributeFromEvent);
}

const setStateFromEvent = (event) => {
Expand Down

0 comments on commit 3529e5c

Please sign in to comment.