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

Audit: DOM stats (total nodes, depth, width) #1673

Merged
merged 12 commits into from
Feb 17, 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
94 changes: 94 additions & 0 deletions lighthouse-cli/test/fixtures/dobetterweb/domtester.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<!doctype html>
<!--
* 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.
-->
<html>
<head>
<title>DoBetterWeb - DOM size tester</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
</head>
<body>
<main>
<section>
<div>
<div>6</div>
</div>
<div>
<div>
<div id="attachshadow">7</div>
</div>
</div>
<div>
<template>
<div><div><div><div>10, but noop in template</div></div></div></div>
</template>
</div>
</section>
</main>
<footer>
<div id="attachshadow-big" class="test this out">4</div>
<div>3</div>
<div></div>
<div></div>
<div></div>
<div></div>
</footer>
<script>
function withShadowDOMTest() {
const el = document.querySelector('#attachshadow');
el.innerHTML = `<div>7</div>`;
el.attachShadow({mode: 'open'}).innerHTML = `
<div>
<div class="here">9</div>
</div>
`;

const el2 = document.querySelector('#attachshadow-big');
el2.attachShadow({mode: 'open'}).innerHTML = `
<div>
<div>6</div>
<div>6</div>
<div>6</div>
<div>6</div>
<div>6</div>
<div>6</div>
<div>6</div>
<div>6</div>
<div>6</div>
</div>
`;
}

function domTest(numNodes=1500) {
const frag = new DocumentFragment();
for (let i = 0; i < numNodes; ++i) {
frag.appendChild(document.createElement('span'));
}
document.body.appendChild(frag);
}

const params = new URLSearchParams(location.search);
if (params.has('smallDOM')) {
domTest(1300);
} else if (params.has('largeDOM')) {
domTest(6000);
}
if (params.has('withShadowDOM')) {
withShadowDOMTest();
}
</script>
</body>
</html>
45 changes: 45 additions & 0 deletions lighthouse-cli/test/smokehouse/dobetterweb/dbw-expectations.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,51 @@ module.exports = [
}
}
}
}, {
initialUrl: 'http://localhost:10200/dobetterweb/domtester.html?smallDOM',
Copy link
Collaborator

Choose a reason for hiding this comment

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

yay for moving out into some new testers! 🎉

url: 'http://localhost:10200/dobetterweb/domtester.html?smallDOM',
audits: {
'dom-size': {
score: 100,
extendedInfo: {
value: {
0: {value: '1,323'},
1: {value: '7'},
2: {value: '1,303'}
}
}
}
}
}, {
initialUrl: 'http://localhost:10200/dobetterweb/domtester.html?largeDOM&withShadowDOM',
url: 'http://localhost:10200/dobetterweb/domtester.html?largeDOM&withShadowDOM',
audits: {
'dom-size': {
score: 0,
extendedInfo: {
value: {
0: {value: '6,024'},
1: {value: '9'},
2: {value: '6,003'}
}
}
}
}
}, {
initialUrl: 'http://localhost:10200/dobetterweb/domtester.html?withShadowDOM',
url: 'http://localhost:10200/dobetterweb/domtester.html?withShadowDOM',
audits: {
'dom-size': {
score: 100,
extendedInfo: {
value: {
0: {value: '24'},
1: {value: '9'},
2: {value: '9'}
}
}
}
}
}, {
initialUrl: 'http://localhost:10200/online-only.html',
url: 'http://localhost:10200/online-only.html',
Expand Down
112 changes: 112 additions & 0 deletions lighthouse-core/audits/dobetterweb/dom-size.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/**
* @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.
*/

/**
* @fileoverview Audits a page to see how the size of DOM it creates. Stats like
* tree depth, # children, and total nodes are returned. The score is calculated
* based solely on the total number of nodes found on the page.
*/

'use strict';

const Audit = require('../audit');
const TracingProcessor = require('../../lib/traces/tracing-processor');
const Formatter = require('../../formatters/formatter');

const MAX_DOM_NODES = 1500;
const MAX_DOM_TREE_WIDTH = 60;
const MAX_DOM_TREE_DEPTH = 32;

// Parameters for log-normal CDF scoring. See https://www.desmos.com/calculator/9cyxpm5qgp.
const SCORING_POINT_OF_DIMINISHING_RETURNS = 2400;
const SCORING_MEDIAN = 3000;

class DOMSize extends Audit {
static get MAX_DOM_NODES() {
return MAX_DOM_NODES;
}

/**
* @return {!AuditMeta}
*/
static get meta() {
return {
category: 'Performance',
name: 'dom-size',
description: 'Avoids an excessive DOM size',
optimalValue: DOMSize.MAX_DOM_NODES.toLocaleString() + ' nodes',
helpText: 'Browser engineers recommend pages contain fewer than ' +
`~${DOMSize.MAX_DOM_NODES.toLocaleString()} DOM nodes. The sweet spot is a tree depth < ` +
`${MAX_DOM_TREE_DEPTH} elements and fewer than ${MAX_DOM_TREE_WIDTH} ` +
'children/parent element. A large DOM can increase memory, cause longer ' +
'[style calculations](https://developers.google.com/web/fundamentals/performance/rendering/reduce-the-scope-and-complexity-of-style-calculations), ' +
'and produce costly [layout reflows](https://developers.google.com/speed/articles/reflow). [Learn more](https://developers.google.com/web/fundamentals/performance/rendering/).',
requiredArtifacts: ['DOMStats']
};
}

/**
* @param {!Artifacts} artifacts
* @return {!AuditResult}
*/
static audit(artifacts) {
const stats = artifacts.DOMStats;

/**
* html >
* body >
* div >
* span
*/
const depthSnippet = stats.depth.pathToElement.reduce((str, curr, i) => {
return `${str}\n` + ' '.repeat(i) + `${curr} >`;
}, '').replace(/>$/g, '').trim();
const widthSnippet = 'Element with most children:\n' +
stats.width.pathToElement[stats.width.pathToElement.length - 1];

// Use the CDF of a log-normal distribution for scoring.
// <= 1500: score≈100
// 3000: score=50
// >= 5970: score≈0
const distribution = TracingProcessor.getLogNormalDistribution(
SCORING_MEDIAN, SCORING_POINT_OF_DIMINISHING_RETURNS);
let score = 100 * distribution.computeComplementaryPercentile(stats.totalDOMNodes);

// Clamp the score to 0 <= x <= 100.
score = Math.max(0, Math.min(100, score));

const cards = [
{title: 'Total DOM Nodes', value: stats.totalDOMNodes.toLocaleString()},
{title: 'DOM Depth', value: stats.depth.max.toLocaleString(), snippet: depthSnippet},
{title: 'Maximum Children', value: stats.width.max.toLocaleString(), snippet: widthSnippet}
];

return DOMSize.generateAuditResult({
rawValue: stats.totalDOMNodes,
optimalValue: this.meta.optimalValue,
score: Math.round(score),
displayValue: `${stats.totalDOMNodes.toLocaleString()} nodes`,
extendedInfo: {
formatter: Formatter.SUPPORTED_FORMATS.CARD,
value: cards
}
});
}

}

module.exports = DOMSize;
8 changes: 7 additions & 1 deletion lighthouse-core/config/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"dobetterweb/document-write",
"dobetterweb/geolocation-on-start",
"dobetterweb/notification-on-start",
"dobetterweb/domstats",
"dobetterweb/optimized-images",
"dobetterweb/tags-blocking-first-paint",
"dobetterweb/websql"
Expand Down Expand Up @@ -85,8 +86,9 @@
"byte-efficiency/unused-css-rules",
"byte-efficiency/uses-optimized-images",
"byte-efficiency/uses-responsive-images",
"dobetterweb/external-anchors-use-rel-noopener",
"dobetterweb/appcache-manifest",
"dobetterweb/dom-size",
"dobetterweb/external-anchors-use-rel-noopener",
"dobetterweb/geolocation-on-start",
"dobetterweb/link-blocking-first-paint",
"dobetterweb/no-console-time",
Expand Down Expand Up @@ -378,6 +380,10 @@
"categorizable": false,
"items": [{
"audits": {
"dom-size": {
"expectedValue": 100,
"weight": 1
},
"critical-request-chains": {
"expectedValue": 0,
"weight": 1
Expand Down
50 changes: 50 additions & 0 deletions lighthouse-core/formatters/cards.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* @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 Formatter = require('./formatter');
const path = require('path');
const fs = require('fs');
const html = fs.readFileSync(path.join(__dirname, 'partials/cards.html'), 'utf8');

class Card extends Formatter {
static getFormatter(type) {
switch (type) {
case 'pretty':
return result => {
if (!result || !Array.isArray(result)) {
return '';
}
let output = '';
result.forEach(item => {
output += ` - ${item.title}: ${item.value}\n`;
});
return output;
};

case 'html':
// Returns a handlebars string to be used by the Report.
return html;

default:
throw new Error('Unknown formatter type');
}
}
}

module.exports = Card;
1 change: 1 addition & 0 deletions lighthouse-core/formatters/formatter.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ class Formatter {
static _getFormatters() {
this._formatters = {
accessibility: require('./accessibility'),
card: require('./cards'),
criticalRequestChains: require('./critical-request-chains'),
urllist: require('./url-list'),
null: require('./null-formatter'),
Expand Down
40 changes: 40 additions & 0 deletions lighthouse-core/formatters/partials/cards.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
.cards__container {
--padding: 16px;
display: flex;
flex-wrap: wrap;
}
.scorecard {
display: flex;
align-items: center;
justify-content: center;
flex: 1 1 150px;
flex-direction: column;
padding: calc(var(--padding) / 2);
padding-top: calc(32px + var(--padding) / 2);
border-radius: 3px;
margin-right: var(--padding);
position: relative;
color: var(--secondary-text-color);
line-height: inherit;
border: 1px solid #ebebeb;
}
.scorecard-title {
/*text-transform: uppercase;*/
font-size: var(--subitem-font-size);
line-height: var(--heading-line-height);
background-color: #eee;
position: absolute;
top: 0;
right: 0;
left: 0;
display: flex;
justify-content: center;
align-items: center;
border-bottom: 1px solid #ebebeb;
}
.scorecard-value {
font-size: 24px;
}
.scorecard-summary {
margin-top: calc(var(--padding) / 2);
}
8 changes: 8 additions & 0 deletions lighthouse-core/formatters/partials/cards.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<ul class="subitem__details cards__container">
{{#each this}}
<div class="subitem__detail scorecard" {{#if snippet}}title="{{snippet}}"{{/if}}>
Copy link
Collaborator

Choose a reason for hiding this comment

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

if it will always be the title can we rename snippet to title?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I reserved title for the card title. Also wanted to make it obvious this was a code snippet.

Copy link
Collaborator

Choose a reason for hiding this comment

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

oh whoops, alright

<div class="scorecard-title">{{title}}</div>
<div class="scorecard-value">{{value}}</div>
</div>
{{/each}}
</ul>
Loading