forked from SalesforceCommerceCloud/pwa-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-script.js
More file actions
54 lines (45 loc) · 1.59 KB
/
use-script.js
File metadata and controls
54 lines (45 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
* Copyright (c) 2024, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {useEffect, useState} from 'react'
import PropTypes from 'prop-types'
/**
* Custom hook to handle script loading
* @param {string} src - The source URL for the script
* @returns {Object} The script load status
*/
const useScript = (src) => {
const [scriptLoadStatus, setScriptLoadStatus] = useState({loaded: false, error: false})
// Effect to load and initialize the script
useEffect(() => {
if (!src) {
return
}
// Check if script already exists
const scriptAlreadyOnPage = document.querySelector(`script[src="${src}"]`)
if (!scriptAlreadyOnPage) {
const script = document.createElement('script')
script.src = src
script.async = true
script.setAttribute('data-status', 'loading')
document.body.appendChild(script)
const onScriptLoad = (event) => {
const loadStatus = event.type === 'load' ? 'ready' : 'error'
setScriptLoadStatus({
loaded: loadStatus === 'ready',
error: loadStatus === 'error'
})
}
script.addEventListener('load', onScriptLoad)
script.addEventListener('error', onScriptLoad)
}
}, [src])
return scriptLoadStatus
}
useScript.propTypes = {
src: PropTypes.string
}
export default useScript