MCPcopy
hub / github.com/ampproject/amphtml / loadPromise

Function loadPromise

src/utils/event-helper.js:156–215  ·  view source on GitHub ↗
(eleOrWindow)

Source from the content-addressed store, hash-verified

154 * @template T
155 */
156export function loadPromise(eleOrWindow) {
157 let unlistenLoad;
158 let unlistenError;
159 if (isLoaded(eleOrWindow)) {
160 return Promise.resolve(eleOrWindow);
161 }
162 const isMediaElement = isHTMLMediaElement(eleOrWindow);
163 if (
164 isMediaElement &&
165 eleOrWindow[MEDIA_LOAD_FAILURE_SRC_PROPERTY] === eleOrWindow.currentSrc
166 ) {
167 return Promise.reject(eleOrWindow);
168 }
169 const loadingPromise = new Promise((resolve, reject) => {
170 // Listen once since IE 5/6/7 fire the onload event continuously for
171 // animated GIFs.
172 if (isMediaElement) {
173 // The following event can be triggered by the media or one of its
174 // sources. Using capture is required as the media events do not bubble.
175 unlistenLoad = listenOnce(eleOrWindow, 'loadedmetadata', resolve, {
176 capture: true,
177 });
178 } else {
179 unlistenLoad = listenOnce(eleOrWindow, 'load', resolve);
180 }
181 // Don't unlisten on error for Windows.
182 if (!eleOrWindow.tagName) {
183 return;
184 }
185 let errorTarget = eleOrWindow;
186 // If the media element has no `src`, it will try to load the sources in
187 // document order. If the last source errors, then the media element
188 // loading errored.
189 if (isMediaElement && !eleOrWindow.hasAttribute('src')) {
190 errorTarget = lastChildElement(
191 eleOrWindow,
192 (child) => child.tagName === 'SOURCE'
193 );
194 if (!errorTarget) {
195 return reject(new Error('Media has no source.'));
196 }
197 }
198 unlistenError = listenOnce(errorTarget, 'error', reject);
199 });
200
201 return loadingPromise.then(
202 () => {
203 if (unlistenError) {
204 unlistenError();
205 }
206 return eleOrWindow;
207 },
208 () => {
209 if (unlistenLoad) {
210 unlistenLoad();
211 }
212 failedToLoad(eleOrWindow);
213 }

Callers 15

test-service.jsFile · 0.90
test-viewport.jsFile · 0.90
waitForMutationObserverFunction · 0.90
test-resources.jsFile · 0.90
test-query.jsFile · 0.90
test-dom.jsFile · 0.90
loadScriptFunction · 0.90
loadPromiseMethod · 0.90
getTimingDataAsyncFunction · 0.90

Calls 7

lastChildElementFunction · 0.90
isLoadedFunction · 0.85
isHTMLMediaElementFunction · 0.85
listenOnceFunction · 0.85
failedToLoadFunction · 0.85
resolveMethod · 0.80
thenMethod · 0.45

Tested by

no test coverage detected