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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new-audit(unminified-javascript): detect savings from minifcation #3950

Merged
merged 4 commits into from
Dec 20, 2017
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions lighthouse-cli/test/smokehouse/byte-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ module.exports = {
'uses-webp-images',
'uses-optimized-images',
'uses-responsive-images',
'unminified-javascript',
'unused-css-rules',
'unused-javascript',
],
Expand Down
11 changes: 11 additions & 0 deletions lighthouse-cli/test/smokehouse/byte-efficiency/expectations.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,17 @@ module.exports = [
initialUrl: 'http://localhost:10200/byte-efficiency/tester.html',
url: 'http://localhost:10200/byte-efficiency/tester.html',
audits: {
'unminified-javascript': {
score: '<100',
extendedInfo: {
value: {
wastedKb: 14,
results: {
length: 1,
},
},
},
},
'unused-css-rules': {
score: '<100',
extendedInfo: {
Expand Down
95 changes: 95 additions & 0 deletions lighthouse-core/audits/byte-efficiency/unminified-javascript.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/**
* @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 ByteEfficiencyAudit = require('./byte-efficiency-audit');
const esprima = require('esprima');

const IGNORE_THRESHOLD_IN_PERCENT = 10;
const IGNORE_THRESHOLD_IN_BYTES = 2048;

/**
* @fileOverview Estimates minification savings by determining the ratio of parseable JS tokens to the
* length of the entire string. Though simple, this method is quite accurate at identifying whether
* a script was already minified and offers a relatively conservative minification estimate (our two
* primary goals).
*
* This audit only examines scripts that were independent network requests and not inlined or eval'd.
*
* See https://github.com/GoogleChrome/lighthouse/pull/3950#issue-277887798 for stats on accuracy.
*/
class UnminifiedJavaScript extends ByteEfficiencyAudit {
/**
* @return {!AuditMeta}
*/
static get meta() {
return {
name: 'unminified-javascript',
description: 'Minify JavaScript',
informative: true,
helpText: 'Minifying JavaScript files can reduce payload sizes and script parse time.' +
'[Learn more](https://developers.google.com/speed/docs/insights/MinifyResources).',
requiredArtifacts: ['Scripts', 'devtoolsLogs'],
};
}

/**
Copy link
Member

Choose a reason for hiding this comment

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

can you add a comment here explaining the basic approach? using the description from this PR works for me.

let's also call out that inline scripts are not evaluated. (i dont think it matters in practice, but since other audits of ours include inline scripts we should just be explicit)

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

yeah sounds good 👍

done

* @param {string} scriptContent
* @return {{minifiedLength: number, contentLength: number}}
*/
static computeWaste(scriptContent, networkRecord) {
const contentLength = scriptContent.length;
let totalTokenLength = 0;

const tokens = esprima.tokenize(scriptContent);
for (const token of tokens) {
totalTokenLength += token.value.length;
}

const totalBytes = ByteEfficiencyAudit.estimateTransferSize(networkRecord, contentLength,
'script');
const wastedRatio = 1 - totalTokenLength / contentLength;
const wastedBytes = Math.round(totalBytes * wastedRatio);

return {
url: networkRecord.url,
totalBytes,
wastedBytes,
wastedPercent: 100 * wastedRatio,
};
}

/**
* @param {!Artifacts} artifacts
* @return {!Audit.HeadingsResult}
*/
static audit_(artifacts, networkRecords) {
const results = [];
for (const [requestId, scriptContent] of artifacts.Scripts.entries()) {
const networkRecord = networkRecords.find(record => record.requestId === requestId);
if (!networkRecord || !scriptContent) continue;

const result = UnminifiedJavaScript.computeWaste(scriptContent, networkRecord);

// If the ratio is minimal, the file is likely already minified, so ignore it.
// If the total number of bytes to be saved is quite small, it's also safe to ignore.
if (result.wastedPercent < IGNORE_THRESHOLD_IN_PERCENT ||
result.wastedBytes < IGNORE_THRESHOLD_IN_BYTES) continue;
results.push(result);
}

return {
results,
headings: [
{key: 'url', itemType: 'url', text: 'URL'},
{key: 'totalKb', itemType: 'text', text: 'Original'},
{key: 'potentialSavings', itemType: 'text', text: 'Potential Savings'},
],
};
}
}

module.exports = UnminifiedJavaScript;
3 changes: 3 additions & 0 deletions lighthouse-core/config/default.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ module.exports = {
useThrottling: true,
gatherers: [
'url',
'scripts',
'viewport',
'viewport-dimensions',
'theme-color',
Expand Down Expand Up @@ -144,6 +145,7 @@ module.exports = {
'byte-efficiency/uses-long-cache-ttl',
'byte-efficiency/total-byte-weight',
'byte-efficiency/offscreen-images',
'byte-efficiency/unminified-javascript',
'byte-efficiency/uses-webp-images',
'byte-efficiency/uses-optimized-images',
'byte-efficiency/uses-request-compression',
Expand Down Expand Up @@ -260,6 +262,7 @@ module.exports = {
{id: 'script-blocking-first-paint', weight: 0, group: 'perf-hint'},
{id: 'uses-responsive-images', weight: 0, group: 'perf-hint'},
{id: 'offscreen-images', weight: 0, group: 'perf-hint'},
{id: 'unminified-javascript', weight: 0, group: 'perf-hint'},
{id: 'uses-optimized-images', weight: 0, group: 'perf-hint'},
{id: 'uses-webp-images', weight: 0, group: 'perf-hint'},
{id: 'uses-request-compression', weight: 0, group: 'perf-hint'},
Expand Down
42 changes: 42 additions & 0 deletions lighthouse-core/gather/gatherers/scripts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* @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 Gatherer = require('./gatherer');
const WebInspector = require('../../lib/web-inspector');

/**
* @fileoverview Gets JavaScript file content
*/
class Scripts extends Gatherer {
/**
* @param {{driver: !Driver}} options
* @param {{networkRecords: !Array<WebInspector.NetworkRequest}} traceData
* @return {!Promise<!Map<string, string>>}
*/
afterPass(options, traceData) {
const driver = options.driver;

const scriptContentMap = new Map();
const scriptRecords = traceData.networkRecords
.filter(record => record.resourceType() === WebInspector.resourceTypes.Script);

return scriptRecords.reduce((promise, record) => {
return promise
.then(() => {
return driver.getRequestContent(record.requestId)
.catch(_ => null)
.then(content => {
if (!content) return;
scriptContentMap.set(record.requestId, content);
});
})
.then(() => scriptContentMap);
}, Promise.resolve(scriptContentMap));
}
}

module.exports = Scripts;
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/**
* @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 KB = 1024;
const UnminifiedJavascriptAudit =
require('../../../audits/byte-efficiency/unminified-javascript.js');
const assert = require('assert');

/* eslint-env mocha */

const _resourceType = {_name: 'script'};
describe('Page uses optimized responses', () => {
it('fails when given unminified scripts', () => {
const auditResult = UnminifiedJavascriptAudit.audit_({
Scripts: new Map([
[
'123.1',
`
var foo = new Set();
foo.add(1);
foo.add(2);

if (foo.has(2)) {
console.log('hello!')
}
`,
],
[
'123.2',
`
const foo = new Set();
foo.add(1);

async function go() {
await foo.has(1)
console.log('yay esnext!')
}
`,
],
]),
}, [
{requestId: '123.1', url: 'foo.js', _transferSize: 20 * KB, _resourceType},
{requestId: '123.2', url: 'other.js', _transferSize: 50 * KB, _resourceType},
]);

assert.equal(auditResult.results.length, 2);
assert.equal(auditResult.results[0].url, 'foo.js');
assert.equal(Math.round(auditResult.results[0].wastedPercent), 57);
assert.equal(Math.round(auditResult.results[0].wastedBytes / 1024), 11);
assert.equal(auditResult.results[1].url, 'other.js');
assert.equal(Math.round(auditResult.results[1].wastedPercent), 53);
assert.equal(Math.round(auditResult.results[1].wastedBytes / 1024), 27);
});

it('passes when scripts are already minified', () => {
const auditResult = UnminifiedJavascriptAudit.audit_({
Scripts: new Map([
[
'123.1',
'var f=new Set();f.add(1);f.add(2);if(f.has(2))console.log(1234)',
],
[
'123.2',
`
const foo = new Set();
foo.add(1);

async function go() {
await foo.has(1)
console.log('yay esnext!')
}
`,
],
[
'123.3',
'for{(wtf',
],
]),
}, [
{requestId: '123.1', url: 'foo.js', _transferSize: 20 * KB, _resourceType},
{requestId: '123.2', url: 'other.js', _transferSize: 3 * KB, _resourceType},
{requestId: '123.3', url: 'invalid.js', _transferSize: 20 * KB, _resourceType},
]);

assert.equal(auditResult.results.length, 0);
});
});
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
"chrome-launcher": "0.8.1",
"configstore": "^3.1.1",
"devtools-timeline-model": "1.1.6",
"esprima": "^4.0.0",
"http-link-header": "^0.8.0",
"inquirer": "^3.3.0",
"jpeg-js": "0.1.2",
Expand Down