Skip to content

Commit

Permalink
core(image-elements): cache naturalSize results (#9818)
Browse files Browse the repository at this point in the history
  • Loading branch information
paulirish authored and brendankenny committed Oct 11, 2019
1 parent 6d56a70 commit e9410a1
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lighthouse-core/gather/gatherers/image-elements.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,18 +130,29 @@ function determineNaturalSize(url) {
}

class ImageElements extends Gatherer {
constructor() {
super();
/** @type {Map<string, {naturalWidth: number, naturalHeight: number}>} */
this._naturalSizeCache = new Map();
}

/**
* @param {Driver} driver
* @param {LH.Artifacts.ImageElement} element
* @return {Promise<LH.Artifacts.ImageElement>}
*/
async fetchElementWithSizeInformation(driver, element) {
const url = JSON.stringify(element.src);
if (this._naturalSizeCache.has(url)) {
return Object.assign(element, this._naturalSizeCache.get(url));
}

try {
// We don't want this to take forever, 250ms should be enough for images that are cached
driver.setNextProtocolTimeout(250);
/** @type {{naturalWidth: number, naturalHeight: number}} */
const size = await driver.evaluateAsync(`(${determineNaturalSize.toString()})(${url})`);
this._naturalSizeCache.set(url, size);
return Object.assign(element, size);
} catch (_) {
// determineNaturalSize fails on invalid images, which we treat as non-visible
Expand Down

0 comments on commit e9410a1

Please sign in to comment.