summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer.cc
blob: 40d89cf594a5d6068fc9d609f29d9a8e6c80d51a (plain)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/core/html/lazy_load_frame_observer.h"

#include <limits>

#include "base/metrics/histogram_macros.h"
#include "third_party/blink/public/platform/web_effective_connection_type.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/frame/frame.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/geometry/dom_rect_read_only.h"
#include "third_party/blink/renderer/core/html/html_frame_owner_element.h"
#include "third_party/blink/renderer/core/intersection_observer/intersection_observer.h"
#include "third_party/blink/renderer/core/intersection_observer/intersection_observer_entry.h"
#include "third_party/blink/renderer/core/loader/frame_load_request.h"
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/heap/visitor.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"

namespace blink {

namespace {

// Determine if the |bounding_client_rect| for a frame indicates that the frame
// is probably hidden according to some experimental heuristics. Since hidden
// frames are often used for analytics or communication, and lazily loading them
// could break their functionality, so these heuristics are used to recognize
// likely hidden frames and immediately load them so that they can function
// properly.
bool IsFrameProbablyHidden(const DOMRectReadOnly& bounding_client_rect,
                           const Element& element) {
  // Tiny frames that are 4x4 or smaller are likely not intended to be seen by
  // the user. Note that this condition includes frames marked as
  // "display:none", since those frames would have dimensions of 0x0.
  if (bounding_client_rect.width() < 4.1 || bounding_client_rect.height() < 4.1)
    return true;

  // Frames that are positioned completely off the page above or to the left are
  // likely never intended to be visible to the user.
  if (bounding_client_rect.right() < 0.0 || bounding_client_rect.bottom() < 0.0)
    return true;

  const ComputedStyle* style = element.GetComputedStyle();
  if (style) {
    switch (style->Visibility()) {
      case EVisibility::kHidden:
      case EVisibility::kCollapse:
        return true;
      case EVisibility::kVisible:
        break;
    }
  }

  return false;
}

int GetLazyFrameLoadingViewportDistanceThresholdPx(const Document& document) {
  const Settings* settings = document.GetSettings();
  if (!settings)
    return 0;

  DCHECK(document.GetFrame() && document.GetFrame()->Client());
  switch (document.GetFrame()->Client()->GetEffectiveConnectionType()) {
    case WebEffectiveConnectionType::kTypeUnknown:
      return settings->GetLazyFrameLoadingDistanceThresholdPxUnknown();
    case WebEffectiveConnectionType::kTypeOffline:
      return settings->GetLazyFrameLoadingDistanceThresholdPxOffline();
    case WebEffectiveConnectionType::kTypeSlow2G:
      return settings->GetLazyFrameLoadingDistanceThresholdPxSlow2G();
    case WebEffectiveConnectionType::kType2G:
      return settings->GetLazyFrameLoadingDistanceThresholdPx2G();
    case WebEffectiveConnectionType::kType3G:
      return settings->GetLazyFrameLoadingDistanceThresholdPx3G();
    case WebEffectiveConnectionType::kType4G:
      return settings->GetLazyFrameLoadingDistanceThresholdPx4G();
  }
  NOTREACHED();
  return 0;
}

}  // namespace

struct LazyLoadFrameObserver::LazyLoadRequestInfo {
  LazyLoadRequestInfo(const ResourceRequest& resource_request,
                      WebFrameLoadType frame_load_type)
      : resource_request(resource_request), frame_load_type(frame_load_type) {}

  const ResourceRequest resource_request;
  const WebFrameLoadType frame_load_type;
};

LazyLoadFrameObserver::LazyLoadFrameObserver(HTMLFrameOwnerElement& element)
    : element_(&element) {}

LazyLoadFrameObserver::~LazyLoadFrameObserver() = default;

void LazyLoadFrameObserver::DeferLoadUntilNearViewport(
    const ResourceRequest& resource_request,
    WebFrameLoadType frame_load_type) {
  DCHECK(!lazy_load_intersection_observer_);
  DCHECK(!lazy_load_request_info_);
  lazy_load_request_info_ =
      std::make_unique<LazyLoadRequestInfo>(resource_request, frame_load_type);

  was_recorded_as_deferred_ = false;

  lazy_load_intersection_observer_ = IntersectionObserver::Create(
      {Length(GetLazyFrameLoadingViewportDistanceThresholdPx(
                  element_->GetDocument()),
              kFixed)},
      {std::numeric_limits<float>::min()}, &element_->GetDocument(),
      WTF::BindRepeating(&LazyLoadFrameObserver::LoadIfHiddenOrNearViewport,
                         WrapWeakPersistent(this)));

  lazy_load_intersection_observer_->observe(element_);
}

void LazyLoadFrameObserver::CancelPendingLazyLoad() {
  lazy_load_request_info_.reset();

  if (!lazy_load_intersection_observer_)
    return;
  lazy_load_intersection_observer_->disconnect();
  lazy_load_intersection_observer_.Clear();
}

void LazyLoadFrameObserver::LoadIfHiddenOrNearViewport(
    const HeapVector<Member<IntersectionObserverEntry>>& entries) {
  DCHECK(!entries.IsEmpty());
  DCHECK_EQ(element_, entries.back()->target());

  if (entries.back()->isIntersecting()) {
    RecordInitialDeferralAction(
        FrameInitialDeferralAction::kLoadedNearOrInViewport);
  } else if (IsFrameProbablyHidden(*entries.back()->boundingClientRect(),
                                   *element_)) {
    RecordInitialDeferralAction(FrameInitialDeferralAction::kLoadedHidden);
  } else {
    RecordInitialDeferralAction(FrameInitialDeferralAction::kDeferred);
    return;
  }

  LoadImmediately();
}

void LazyLoadFrameObserver::LoadImmediately() {
  DCHECK(IsLazyLoadPending());
  DCHECK(lazy_load_request_info_);

  if (was_recorded_as_deferred_) {
    DCHECK(element_->GetDocument().GetFrame());
    DCHECK(element_->GetDocument().GetFrame()->Client());

    UMA_HISTOGRAM_ENUMERATION(
        "Blink.LazyLoad.CrossOriginFrames.LoadStartedAfterBeingDeferred",
        element_->GetDocument()
            .GetFrame()
            ->Client()
            ->GetEffectiveConnectionType());
  }

  std::unique_ptr<LazyLoadRequestInfo> scoped_request_info =
      std::move(lazy_load_request_info_);

  // The content frame of the element should not have changed, since any
  // pending lazy load should have been already been cancelled in
  // DisconnectContentFrame() if the content frame changes.
  DCHECK(element_->ContentFrame());

  // Note that calling FrameLoader::StartNavigation() causes the
  // |lazy_load_intersection_observer_| to be disconnected.
  ToLocalFrame(element_->ContentFrame())
      ->Loader()
      .StartNavigation(FrameLoadRequest(&element_->GetDocument(),
                                        scoped_request_info->resource_request),
                       scoped_request_info->frame_load_type);

  DCHECK(!IsLazyLoadPending());
}

void LazyLoadFrameObserver::StartTrackingVisibilityMetrics() {
  DCHECK(time_when_first_visible_.is_null());
  DCHECK(!visibility_metrics_observer_);

  visibility_metrics_observer_ = IntersectionObserver::Create(
      {}, {std::numeric_limits<float>::min()}, &element_->GetDocument(),
      WTF::BindRepeating(
          &LazyLoadFrameObserver::RecordMetricsOnVisibilityChanged,
          WrapWeakPersistent(this)));

  visibility_metrics_observer_->observe(element_);
}

void LazyLoadFrameObserver::RecordMetricsOnVisibilityChanged(
    const HeapVector<Member<IntersectionObserverEntry>>& entries) {
  DCHECK(!entries.IsEmpty());
  DCHECK_EQ(element_, entries.back()->target());

  if (IsFrameProbablyHidden(*entries.back()->boundingClientRect(), *element_)) {
    visibility_metrics_observer_->disconnect();
    visibility_metrics_observer_.Clear();
    return;
  }

  if (!has_above_the_fold_been_set_) {
    is_initially_above_the_fold_ = entries.back()->isIntersecting();
    has_above_the_fold_been_set_ = true;
  }

  if (!entries.back()->isIntersecting())
    return;

  DCHECK(time_when_first_visible_.is_null());
  time_when_first_visible_ = CurrentTimeTicks();
  RecordVisibilityMetricsIfLoadedAndVisible();

  visibility_metrics_observer_->disconnect();
  visibility_metrics_observer_.Clear();

  // The below metrics require getting the effective connection type from the
  // parent frame, so return early here if there's no parent frame to get the
  // effective connection type from.
  if (!element_->GetDocument().GetFrame())
    return;

  DCHECK(element_->GetDocument().GetFrame()->Client());

  // On slow networks, iframes might not finish loading by the time the user
  // leaves the page, so the visible load time metrics samples won't represent
  // the slowest frames. To remedy this, record how often below the fold
  // lazyload-eligible frames become visible before they've finished loading.
  // This isn't recorded for above the fold frames since basically every above
  // the fold frame would be visible before they finish loading.
  if (time_when_first_load_finished_.is_null() &&
      !is_initially_above_the_fold_) {
    // Note: If the WebEffectiveConnectionType enum ever gets out of sync with
    // net::EffectiveConnectionType, then this will have to be updated to record
    // the sample in terms of net::EffectiveConnectionType instead of
    // WebEffectiveConnectionType.
    UMA_HISTOGRAM_ENUMERATION(
        "Blink.VisibleBeforeLoaded.LazyLoadEligibleFrames.BelowTheFold",
        element_->GetDocument()
            .GetFrame()
            ->Client()
            ->GetEffectiveConnectionType());
  }

  if (was_recorded_as_deferred_) {
    UMA_HISTOGRAM_ENUMERATION(
        "Blink.LazyLoad.CrossOriginFrames.VisibleAfterBeingDeferred",
        element_->GetDocument()
            .GetFrame()
            ->Client()
            ->GetEffectiveConnectionType());
  }
}

void LazyLoadFrameObserver::RecordMetricsOnLoadFinished() {
  if (!time_when_first_load_finished_.is_null())
    return;
  time_when_first_load_finished_ = CurrentTimeTicks();
  RecordVisibilityMetricsIfLoadedAndVisible();
}

void LazyLoadFrameObserver::RecordVisibilityMetricsIfLoadedAndVisible() {
  if (time_when_first_load_finished_.is_null() ||
      time_when_first_visible_.is_null() ||
      !element_->GetDocument().GetFrame()) {
    return;
  }

  DCHECK(has_above_the_fold_been_set_);

  TimeDelta visible_load_delay =
      time_when_first_load_finished_ - time_when_first_visible_;
  if (visible_load_delay < TimeDelta())
    visible_load_delay = TimeDelta();

  switch (element_->GetDocument()
              .GetFrame()
              ->Client()
              ->GetEffectiveConnectionType()) {
    case WebEffectiveConnectionType::kTypeSlow2G:
      if (is_initially_above_the_fold_) {
        UMA_HISTOGRAM_MEDIUM_TIMES(
            "Blink.VisibleLoadTime.LazyLoadEligibleFrames.AboveTheFold.Slow2G",
            visible_load_delay);
      } else {
        UMA_HISTOGRAM_MEDIUM_TIMES(
            "Blink.VisibleLoadTime.LazyLoadEligibleFrames.BelowTheFold.Slow2G",
            visible_load_delay);
      }
      break;

    case WebEffectiveConnectionType::kType2G:
      if (is_initially_above_the_fold_) {
        UMA_HISTOGRAM_MEDIUM_TIMES(
            "Blink.VisibleLoadTime.LazyLoadEligibleFrames.AboveTheFold.2G",
            visible_load_delay);
      } else {
        UMA_HISTOGRAM_MEDIUM_TIMES(
            "Blink.VisibleLoadTime.LazyLoadEligibleFrames.BelowTheFold.2G",
            visible_load_delay);
      }
      break;

    case WebEffectiveConnectionType::kType3G:
      if (is_initially_above_the_fold_) {
        UMA_HISTOGRAM_MEDIUM_TIMES(
            "Blink.VisibleLoadTime.LazyLoadEligibleFrames.AboveTheFold.3G",
            visible_load_delay);
      } else {
        UMA_HISTOGRAM_MEDIUM_TIMES(
            "Blink.VisibleLoadTime.LazyLoadEligibleFrames.BelowTheFold.3G",
            visible_load_delay);
      }
      break;

    case WebEffectiveConnectionType::kType4G:
      if (is_initially_above_the_fold_) {
        UMA_HISTOGRAM_MEDIUM_TIMES(
            "Blink.VisibleLoadTime.LazyLoadEligibleFrames.AboveTheFold.4G",
            visible_load_delay);
      } else {
        UMA_HISTOGRAM_MEDIUM_TIMES(
            "Blink.VisibleLoadTime.LazyLoadEligibleFrames.BelowTheFold.4G",
            visible_load_delay);
      }
      break;

    case WebEffectiveConnectionType::kTypeUnknown:
    case WebEffectiveConnectionType::kTypeOffline:
      // No VisibleLoadTime histograms are recorded for these effective
      // connection types.
      break;
  }
}

void LazyLoadFrameObserver::RecordInitialDeferralAction(
    FrameInitialDeferralAction action) {
  if (was_recorded_as_deferred_)
    return;

  DCHECK(element_->GetDocument().GetFrame());
  DCHECK(element_->GetDocument().GetFrame()->Client());

  switch (element_->GetDocument()
              .GetFrame()
              ->Client()
              ->GetEffectiveConnectionType()) {
    case WebEffectiveConnectionType::kTypeUnknown:
      UMA_HISTOGRAM_ENUMERATION(
          "Blink.LazyLoad.CrossOriginFrames.InitialDeferralAction.Unknown",
          action);
      break;
    case WebEffectiveConnectionType::kTypeOffline:
      UMA_HISTOGRAM_ENUMERATION(
          "Blink.LazyLoad.CrossOriginFrames.InitialDeferralAction.Offline",
          action);
      break;
    case WebEffectiveConnectionType::kTypeSlow2G:
      UMA_HISTOGRAM_ENUMERATION(
          "Blink.LazyLoad.CrossOriginFrames.InitialDeferralAction.Slow2G",
          action);
      break;
    case WebEffectiveConnectionType::kType2G:
      UMA_HISTOGRAM_ENUMERATION(
          "Blink.LazyLoad.CrossOriginFrames.InitialDeferralAction.2G", action);
      break;
    case WebEffectiveConnectionType::kType3G:
      UMA_HISTOGRAM_ENUMERATION(
          "Blink.LazyLoad.CrossOriginFrames.InitialDeferralAction.3G", action);
      break;
    case WebEffectiveConnectionType::kType4G:
      UMA_HISTOGRAM_ENUMERATION(
          "Blink.LazyLoad.CrossOriginFrames.InitialDeferralAction.4G", action);
      break;
  }

  if (action == FrameInitialDeferralAction::kDeferred)
    was_recorded_as_deferred_ = true;
}

void LazyLoadFrameObserver::Trace(Visitor* visitor) {
  visitor->Trace(element_);
  visitor->Trace(lazy_load_intersection_observer_);
  visitor->Trace(visibility_metrics_observer_);
}

}  // namespace blink