Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
new-audit(unminified-javascript): detect savings from minifcation (#3950
- Loading branch information
1 parent
c206e0a
commit 017c9c1
Showing
7 changed files
with
244 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
95 changes: 95 additions & 0 deletions
95
lighthouse-core/audits/byte-efficiency/unminified-javascript.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'], | ||
}; | ||
} | ||
|
||
/** | ||
* @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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
91 changes: 91 additions & 0 deletions
91
lighthouse-core/test/audits/byte-efficiency/unminified-javascript-test.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters