Skip to content

Commit

Permalink
feat: beef up useScript to better load a script async
Browse files Browse the repository at this point in the history
  • Loading branch information
jerelmiller committed Sep 25, 2020
1 parent 45e22b7 commit c942c60
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions src/hooks/useScript.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,33 @@
import { useEffect, useState } from 'react';
import useShallowMemo from './useShallowMemo';

const useScript = (src) => {
const useScript = (src, options) => {
const { attributes = {}, async: isAsync = true, crossOrigin } = options || {};
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState(null);
const attrs = useShallowMemo(() => attributes, [attributes]);

useEffect(() => {
const script = window.document.createElement('script');

script.async = true;
script.crossOrigin = 'anonymous';
script.onload = () => setLoaded(true);
script.async = isAsync;
script.crossOrigin = crossOrigin;
script.onload = () => {
setLoaded(true);
};
script.onerror = setError;
script.src = src;

Object.entries(attrs).forEach(([attribute, value]) =>
script.setAttribute(attribute, value)
);

document.body.appendChild(script);

return () => document.body.removeChild(script);
}, [src]);
}, [src, attrs, isAsync, crossOrigin]);

return loaded;
return [loaded, { error }];
};

export default useScript;

0 comments on commit c942c60

Please sign in to comment.