Skip to content

Commit

Permalink
move out of WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
patrickhulce committed Dec 7, 2017
1 parent 321df67 commit fd547cd
Show file tree
Hide file tree
Showing 5 changed files with 117 additions and 17 deletions.
1 change: 1 addition & 0 deletions lighthouse-cli/test/smokehouse/byte-config.js
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
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
26 changes: 12 additions & 14 deletions lighthouse-core/audits/byte-efficiency/unminified-javascript.js
Expand Up @@ -18,9 +18,10 @@ class UnminifiedJavaScript extends ByteEfficiencyAudit {
static get meta() {
return {
name: 'unminified-javascript',
description: 'Unminified JavaScript',
description: 'Minify JavaScript',
informative: true,
helpText: 'Minify JavaScript to save network bytes.',
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'],
};
}
Expand All @@ -31,21 +32,16 @@ class UnminifiedJavaScript extends ByteEfficiencyAudit {
*/
static computeWaste(scriptContent, networkRecord) {
const contentLength = scriptContent.length;
let tokenLength = 0;
let tokenLengthWithMangling = 0;
let totalTokenLength = 0;

const tokens = esprima.tokenize(scriptContent);
for (const token of tokens) {
tokenLength += token.value.length;
// assume all identifiers could be reduced to a single character
tokenLengthWithMangling += token.type === 'Identifier' ? 1 : token.value.length;
totalTokenLength += token.value.length;
}

if (1 - tokenLength / contentLength < IGNORE_THRESHOLD_IN_PERCENT) return null;

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

return {
Expand All @@ -61,15 +57,17 @@ class UnminifiedJavaScript extends ByteEfficiencyAudit {
* @return {!Audit.HeadingsResult}
*/
static audit_(artifacts, networkRecords) {
const scriptsByUrl = artifacts.Scripts;

const results = [];
for (const [url, scriptContent] of scriptsByUrl.entries()) {
for (const [url, scriptContent] of artifacts.Scripts.entries()) {
const networkRecord = networkRecords.find(record => record.url === url);
if (!networkRecord || !scriptContent) continue;

const result = UnminifiedJavaScript.computeWaste(scriptContent, networkRecord);
if (!result || result.wastedBytes < IGNORE_THRESHOLD_IN_BYTES) continue;

// 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.wastedRatio < IGNORE_THRESHOLD_IN_PERCENT ||
result.wastedBytes < IGNORE_THRESHOLD_IN_BYTES) continue;
results.push(result);
}

Expand Down
6 changes: 3 additions & 3 deletions lighthouse-core/gather/gatherers/scripts.js
Expand Up @@ -9,7 +9,7 @@ const Gatherer = require('./gatherer');
const WebInspector = require('../../lib/web-inspector');

/**
* @fileoverview Gets JavaScript content
* @fileoverview Gets JavaScript file content
*/
class Scripts extends Gatherer {
/**
Expand All @@ -22,13 +22,13 @@ class Scripts extends Gatherer {

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

return scriptRecords.reduce((promise, record) => {
return promise
.then(() => {
return driver.getRequestContent(record.requestId)
.catch(err => null)
.catch(_ => null)
.then(content => {
if (!content) return;
scriptContentMap.set(record.url, content);
Expand Down
@@ -0,0 +1,90 @@
/**
* @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 */

describe('Page uses optimized responses', () => {
it('fails when given unminified scripts', () => {
const auditResult = UnminifiedJavascriptAudit.audit_({
Scripts: new Map([
[
'foo.js',
`
var foo = new Set();
foo.add(1);
foo.add(2);
if (foo.has(2)) {
console.log('hello!')
}
`,
],
[
'other.js',
`
const foo = new Set();
foo.add(1);
async function go() {
await foo.has(1)
console.log('yay esnext!')
}
`,
],
]),
}, [
{url: 'foo.js', _transferSize: 20 * KB, _resourceType: {_name: 'script'}},
{url: 'other.js', _transferSize: 50 * KB, _resourceType: {_name: 'script'}},
]);

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([
[
'foo.js',
'var f=new Set();f.add(1);f.add(2);if(f.has(2))console.log(1234)',
],
[
'other.js',
`
const foo = new Set();
foo.add(1);
async function go() {
await foo.has(1)
console.log('yay esnext!')
}
`,
],
[
'invalid.js',
'for{(wtf',
],
]),
}, [
{url: 'foo.js', _transferSize: 20 * KB, _resourceType: {_name: 'script'}},
{url: 'other.js', _transferSize: 3 * KB, _resourceType: {_name: 'script'}},
{url: 'invalid.js', _transferSize: 20 * KB, _resourceType: {_name: 'script'}},
]);

assert.equal(auditResult.results.length, 0);
});
});

0 comments on commit fd547cd

Please sign in to comment.