MCPcopy
hub / github.com/vercel/next.js / loadScript

Function loadScript

packages/next/src/client/script.tsx:62–156  ·  view source on GitHub ↗
(props: ScriptProps)

Source from the content-addressed store, hash-verified

60}
61
62const 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

Callers 3

handleClientScriptLoadFunction · 0.85
loadLazyScriptFunction · 0.85
ScriptFunction · 0.85

Calls 15

setAttributesFromPropsFunction · 0.90
afterLoadFunction · 0.85
insertStylesheetsFunction · 0.85
thenMethod · 0.80
addEventListenerMethod · 0.80
callMethod · 0.80
isArrayMethod · 0.80
getMethod · 0.65
setMethod · 0.65
resolveFunction · 0.50
rejectFunction · 0.50
onErrorFunction · 0.50

Tested by

no test coverage detected