-
Notifications
You must be signed in to change notification settings - Fork 114
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: beef up useScript to better load a script async
- Loading branch information
1 parent
45e22b7
commit c942c60
Showing
1 changed file
with
18 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |