-
Notifications
You must be signed in to change notification settings - Fork 9.4k
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
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yeah sounds good 👍
done