(props: ScriptProps)
| 60 | } |
| 61 | |
| 62 | const loadScript = (props: ScriptProps): void => { |
| 63 | const { |
| 64 | src, |
| 65 | id, |
| 66 | onLoad = () => {}, |
| 67 | onReady = null, |
| 68 | dangerouslySetInnerHTML, |
| 69 | children = '', |
| 70 | strategy = 'afterInteractive', |
| 71 | onError, |
| 72 | stylesheets, |
| 73 | } = props |
| 74 | |
| 75 | const cacheKey = id || src |
| 76 | |
| 77 | // Script has already loaded |
| 78 | if (cacheKey && LoadCache.has(cacheKey)) { |
| 79 | return |
| 80 | } |
| 81 | |
| 82 | // Contents of this script are already loading/loaded |
| 83 | if (ScriptCache.has(src)) { |
| 84 | LoadCache.add(cacheKey) |
| 85 | // It is possible that multiple `next/script` components all have same "src", but has different "onLoad" |
| 86 | // This is to make sure the same remote script will only load once, but "onLoad" are executed in order |
| 87 | ScriptCache.get(src).then(onLoad, onError) |
| 88 | return |
| 89 | } |
| 90 | |
| 91 | /** Execute after the script first loaded */ |
| 92 | const afterLoad = () => { |
| 93 | // Run onReady for the first time after load event |
| 94 | if (onReady) { |
| 95 | onReady() |
| 96 | } |
| 97 | // add cacheKey to LoadCache when load successfully |
| 98 | LoadCache.add(cacheKey) |
| 99 | } |
| 100 | |
| 101 | const el = document.createElement('script') |
| 102 | |
| 103 | const loadPromise = new Promise<void>((resolve, reject) => { |
| 104 | el.addEventListener('load', function (e) { |
| 105 | resolve() |
| 106 | if (onLoad) { |
| 107 | onLoad.call(this, e) |
| 108 | } |
| 109 | afterLoad() |
| 110 | }) |
| 111 | el.addEventListener('error', function (e) { |
| 112 | reject(e) |
| 113 | }) |
| 114 | }).catch(function (e) { |
| 115 | if (onError) { |
| 116 | onError(e) |
| 117 | } |
| 118 | }) |
| 119 |
no test coverage detected