[go: nahoru, domu]

Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

new_audit: add third party entity summary #9067

Merged
merged 9 commits into from
Jun 25, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions lighthouse-core/audits/bootup-time.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,20 @@ class BootupTime extends Audit {
return urls;
}

/**
* @param {LH.Artifacts.TaskNode} task
* @param {Set<string>} jsURLs
* @return {string}
*/
static getAttributableURLForTask(task, jsURLs) {
const jsURL = task.attributableURLs.find(url => jsURLs.has(url));
const fallbackURL = task.attributableURLs[0];
let attributableURL = jsURL || fallbackURL;
// If we can't find what URL was responsible for this execution, just attribute it to the root page.
if (!attributableURL || attributableURL === 'about:blank') attributableURL = 'Other';
return attributableURL;
}

/**
* @param {LH.Artifacts.TaskNode[]} tasks
* @param {Set<string>} jsURLs
Expand All @@ -87,12 +101,7 @@ class BootupTime extends Audit {
const result = new Map();

for (const task of tasks) {
const jsURL = task.attributableURLs.find(url => jsURLs.has(url));
const fallbackURL = task.attributableURLs[0];
let attributableURL = jsURL || fallbackURL;
// If we can't find what URL was responsible for this execution, just attribute it to the root page.
if (!attributableURL || attributableURL === 'about:blank') attributableURL = 'Other';

const attributableURL = BootupTime.getAttributableURLForTask(task, jsURLs);
const timingByGroupId = result.get(attributableURL) || {};
const originalTime = timingByGroupId[task.group.id] || 0;
timingByGroupId[task.group.id] = originalTime + task.selfTime;
Expand Down
151 changes: 151 additions & 0 deletions lighthouse-core/audits/third-party-summary.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
/**
* @license Copyright 2019 Google Inc. 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.
*/
'use strict';

const thirdPartyWeb = require('third-party-web/httparchive-nostats-subset');

const Audit = require('./audit.js');
const BootupTime = require('./bootup-time.js');
const i18n = require('../lib/i18n/i18n.js');
const NetworkRecords = require('../computed/network-records.js');
const MainThreadTasks = require('../computed/main-thread-tasks.js');

const UIStrings = {
/** Title of a Lighthouse audit that identifies the code on the page that the user doesn't control. This is shown in a list of audits that Lighthouse generates. */
title: 'Third-Party Usage',
/** Description of a Lighthouse audit that identifies the code on the page that the user doesn't control. This is displayed after a user expands the section to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */
description: 'Third-party code can significantly impact load performance. ' +
'Limit the number of redundant third-party providers and only load third-party code after ' +
'your page has primarily finished loading. [Learn more](https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/loading-third-party-javascript/).',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only load third-party code after your page has primarily finished loading

seems kind of strongly worded?

Copy link
Collaborator Author
@patrickhulce patrickhulce Jun 12, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/only/try to/ ?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/only/try to/ ?

sg

/** Label for a table column that displays how much time each row spent executing on the main thread, entries will be the number of milliseconds spent. */
columnMainThreadTime: 'Main Thread Time',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
columnMainThreadTime: 'Main Thread Time',
columnMainThreadTime: 'Main-Thread Time',

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

source? it's mixed at best in our repo too but in https://github.com/WICG/main-thread-scheduling the only thing that has Main-thread is the kebabcase slug and one of the headers while main thread appears 7 times.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

source? it's mixed at best in our repo too but in https://github.com/WICG/main-thread-scheduling the only thing that has Main-thread is the kebabcase slug and one of the headers while main thread appears 7 times.

I mean, I didn't think about it very hard, but it's a phrasal adjective so generally the rule is hyphenate. If it's a known phrase then that's also fine.

馃し鈥嶁檧

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@patrickhulce The hyphen is needed to disambiguate that the word main is part of main thread and not a general adjective that describes thread time. For comparison, in main soccer game, main describes soccer game.

};

const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings);

/** @typedef {import("third-party-web").IEntity} ThirdPartyEntity */

class ThirdPartySummary extends Audit {
/**
* @return {LH.Audit.Meta}
*/
static get meta() {
return {
id: 'third-party-summary',
title: str_(UIStrings.title),
description: str_(UIStrings.description),
scoreDisplayMode: Audit.SCORING_MODES.INFORMATIVE,
requiredArtifacts: ['traces', 'devtoolsLogs'],
};
}

/**
* `third-party-web` throws when the passed in string doesn't appear to have any domain whatsoever.
* We pass in some not-so-url-like things, so make the dependent-code simpler by making this call safe.
* @param {string} url
* @return {ThirdPartyEntity|undefined}
*/
static getEntitySafe(url) {
try {
return thirdPartyWeb.getEntity(url);
} catch (_) {
return undefined;
}
}


/**
*
* @param {Array<LH.Artifacts.NetworkRequest>} networkRecords
* @param {Array<LH.Artifacts.TaskNode>} mainThreadTasks
* @param {number} cpuMultiplier
* @return {Map<ThirdPartyEntity, {mainThreadTime: number, transferSize: number}>}
*/
static getSummaryByEntity(networkRecords, mainThreadTasks, cpuMultiplier) {
/** @type {Map<ThirdPartyEntity, {mainThreadTime: number, transferSize: number}>} */
const entities = new Map();

for (const request of networkRecords) {
const entity = ThirdPartySummary.getEntitySafe(request.url);
if (!entity) continue;

const entityStats = entities.get(entity) || {mainThreadTime: 0, transferSize: 0};
entityStats.transferSize += request.transferSize;
entities.set(entity, entityStats);
}

const jsURLs = BootupTime.getJavaScriptURLs(networkRecords);

for (const task of mainThreadTasks) {
const attributeableURL = BootupTime.getAttributableURLForTask(task, jsURLs);
const entity = ThirdPartySummary.getEntitySafe(attributeableURL);
if (!entity) continue;

const entityStats = entities.get(entity) || {mainThreadTime: 0, transferSize: 0};
entityStats.mainThreadTime += task.selfTime * cpuMultiplier;
entities.set(entity, entityStats);
}

return entities;
}

/**
* @param {LH.Artifacts} artifacts
* @param {LH.Audit.Context} context
* @return {Promise<LH.Audit.Product>}
*/
static async audit(artifacts, context) {
const settings = context.settings || {};
const trace = artifacts.traces[Audit.DEFAULT_PASS];
const devtoolsLog = artifacts.devtoolsLogs[Audit.DEFAULT_PASS];
const networkRecords = await NetworkRecords.request(devtoolsLog, context);
const tasks = await MainThreadTasks.request(trace, context);
const multiplier = settings.throttlingMethod === 'simulate' ?
settings.throttling.cpuSlowdownMultiplier : 1;

const summaryByEntity = ThirdPartySummary.getSummaryByEntity(networkRecords, tasks, multiplier);

const summary = {wastedBytes: 0, wastedMs: 0};

// Sort by a combined measure of bytes + main thread time.
// 1KB ~= 1 ms
/** @param {{transferSize: number, mainThreadTime: number}} stats */
const computeSortValue = stats => stats.transferSize / 1024 + stats.mainThreadTime;

const results = Array.from(summaryByEntity.entries())
.map(([entity, stats]) => {
summary.wastedBytes += stats.transferSize;
summary.wastedMs += stats.mainThreadTime;

return {
entity: /** @type {LH.Audit.Details.LinkValue} */ ({
type: 'link',
text: entity.name,
url: entity.homepage || '',
patrickhulce marked this conversation as resolved.
Show resolved Hide resolved
}),
transferSize: stats.transferSize,
mainThreadTime: stats.mainThreadTime,
};
})
.sort((a, b) => computeSortValue(b) - computeSortValue(a));

/** @type {LH.Audit.Details.Table['headings']} */
const headings = [
{key: 'entity', itemType: 'link', text: str_(i18n.UIStrings.columnURL)},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"URL" doesnt make sense as the column header.. perhaps "Third party" ?

{key: 'transferSize', granularity: 1, itemType: 'bytes',
text: str_(i18n.UIStrings.columnSize)},
{key: 'mainThreadTime', granularity: 1, itemType: 'ms',
text: str_(UIStrings.columnMainThreadTime)},
];

return {
score: Number(results.length === 0),
details: Audit.makeTableDetails(headings, results, summary),
};
}
}

module.exports = ThirdPartySummary;
2 changes: 2 additions & 0 deletions lighthouse-core/config/default-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ const defaultConfig = {
'offline-start-url',
'performance-budget',
'resource-summary',
'third-party-summary',
'manual/pwa-cross-browser',
'manual/pwa-page-transitions',
'manual/pwa-each-page-has-url',
Expand Down Expand Up @@ -391,6 +392,7 @@ const defaultConfig = {
{id: 'font-display', weight: 0, group: 'diagnostics'},
{id: 'performance-budget', weight: 0, group: 'budgets'},
{id: 'resource-summary', weight: 0, group: 'diagnostics'},
{id: 'third-party-summary', weight: 0, group: 'diagnostics'},
// Audits past this point don't belong to a group and will not be shown automatically
{id: 'network-requests', weight: 0},
{id: 'network-rtt', weight: 0},
Expand Down
35 changes: 23 additions & 12 deletions lighthouse-core/report/html/renderer/details-renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,20 +134,31 @@ class DetailsRenderer {
* @return {Element}
*/
_renderLink(details) {
const allowedProtocols = ['https:', 'http:'];
const url = new URL(details.url);
if (!allowedProtocols.includes(url.protocol)) {
// Fall back to just the link text if protocol not allowed.
return this._renderText(details.text);
}
try {
brendankenny marked this conversation as resolved.
Show resolved Hide resolved
const allowedProtocols = ['https:', 'http:'];
const url = new URL(details.url);
if (!allowedProtocols.includes(url.protocol)) {
// Fall back to just the link text if protocol not allowed.
return this._renderText(details.text);
}

const a = this._dom.createElement('a');
a.rel = 'noopener';
a.target = '_blank';
a.textContent = details.text;
a.href = url.href;
const a = this._dom.createElement('a');
a.rel = 'noopener';
a.target = '_blank';
a.textContent = details.text;
a.href = url.href;

return a;
} catch (err) {
if (err.message.startsWith(`Failed to construct 'URL'`) ||
err.message.includes('Invalid URL')) {
// Fall back to text if URL was invalid.
console.warn(`Link details URL "${details.url}" was invalid.`); // eslint-disable-line no-console
return this._renderText(details.text);
}

return a;
throw err;
}
}

/**
Expand Down
58 changes: 58 additions & 0 deletions lighthouse-core/test/audits/third-party-summary-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
* @license Copyright 2017 Google Inc. 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.
*/
'use strict';

const ThirdPartySummary = require('../../audits/third-party-summary.js');

const pwaTrace = require('../fixtures/traces/progressive-app-m60.json');
const pwaDevtoolsLog = require('../fixtures/traces/progressive-app-m60.devtools.log.json');

/* eslint-env jest */
describe('Third party summary', () => {
it('surface the discovered third parties', async () => {
const artifacts = {
devtoolsLogs: {defaultPass: pwaDevtoolsLog},
traces: {defaultPass: pwaTrace},
};

const results = await ThirdPartySummary.audit(artifacts, {computedCache: new Map()});

expect(results.details.items).toEqual([
{
entity: {
text: 'Google Tag Manager',
type: 'link',
url: 'https://marketingplatform.google.com/about/tag-manager/',
},
mainThreadTime: 104.70300000000002,
transferSize: 30827,
},
{
entity: {
text: 'Google Analytics',
type: 'link',
url: 'https://www.google.com/analytics/analytics/',
},
mainThreadTime: 87.576,
transferSize: 20913,
},
]);
});

it('account for simulated throttling', async () => {
const artifacts = {
devtoolsLogs: {defaultPass: pwaDevtoolsLog},
traces: {defaultPass: pwaTrace},
};

const settings = {throttlingMethod: 'simulate', throttling: {cpuSlowdownMultiplier: 4}};
const results = await ThirdPartySummary.audit(artifacts, {computedCache: new Map(), settings});

expect(results.details.items).toHaveLength(2);
expect(Math.round(results.details.items[0].mainThreadTime)).toEqual(419);
expect(Math.round(results.details.items[1].mainThreadTime)).toEqual(350);
});
});
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@
"robots-parser": "^2.0.1",
"semver": "^5.3.0",
"speedline-core": "1.4.2",
"third-party-web": "^0.8.2",
"update-notifier": "^2.5.0",
"ws": "3.3.2",
"yargs": "3.32.0",
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -8063,6 +8063,11 @@ text-table@~0.2.0:
resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4"
integrity sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=

third-party-web@^0.8.2:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

<3

version "0.8.2"
resolved "https://registry.yarnpkg.com/third-party-web/-/third-party-web-0.8.2.tgz#9a13841174a2b2333a15233cb6dbf6553c03a7be"
integrity sha512-HVsNbtlvshQ7X+HwiMvVbes+aH5KwvfncUcUR1EaJ9qENZO/I3fNysunKBUtJZeVoIYq3HHKqeDayarTmBtdPw==

throat@^4.0.0:
version "4.1.0"
resolved "https://registry.yarnpkg.com/throat/-/throat-4.1.0.tgz#89037cbc92c56ab18926e6ba4cbb200e15672a6a"
Expand Down