forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 1
/
concurrent-load.js
74 lines (69 loc) · 2.42 KB
/
concurrent-load.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {timerFor} from '../../../src/services';
import {user} from '../../../src/log';
/**
* Store loading ads info within window to ensure it can be properly stored
* across separately compiled binaries that share load throttling.
* @const ID of window variable used to track 3p ads waiting to load.
*/
const LOADING_ADS_WIN_ID_ = '3pla';
/**
* @param {!Window} win
* @return {boolean} Whether 3p is currently throttled.
*/
export function is3pThrottled(win) {
return !!win[LOADING_ADS_WIN_ID_];
}
/**
* @param {!Element} element
* @return {?number} number if explicit value should be used otherwise super
* default should be used.
*/
export function getAmpAdRenderOutsideViewport(element) {
const rawValue = element.getAttribute('data-loading-strategy');
if (rawValue == null) {
return null;
}
// Ad opts into lazier loading strategy where we only load ads that are
// at closer given number of viewports away.
if (rawValue == 'prefer-viewability-over-views' || rawValue == '') {
return 1.25;
}
const errorMessage =
'Value of data-loading-strategy should be a float number in range ' +
'of [0, 3], but got ' + rawValue;
const viewportNumber =
user().assertNumber(parseFloat(rawValue), errorMessage);
user().assert(viewportNumber >= 0 && viewportNumber <= 3, errorMessage);
return viewportNumber;
}
/**
* Increments loading ads count for throttling.
* @param {!Window} win
* @param {!Promise=} opt_loadingPromise
*/
export function incrementLoadingAds(win, opt_loadingPromise) {
if (win[LOADING_ADS_WIN_ID_] === undefined) {
win[LOADING_ADS_WIN_ID_] = 0;
}
win[LOADING_ADS_WIN_ID_]++;
timerFor(win)
.timeoutPromise(1000, opt_loadingPromise || new Promise(() => {}))
.catch(() => {})
.then(() => {
win[LOADING_ADS_WIN_ID_]--;
});
}