From 60ad77aaf9a58deb44dafabd1c374046f1223f1b Mon Sep 17 00:00:00 2001 From: Gajus Kuizinas Date: Thu, 13 Jul 2017 16:08:54 +0100 Subject: [PATCH] fix: do not re-inline the inline stylesheets (fixes #19) --- src/usus.js | 24 +++++++++++++++++++++++- test/usus.js | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/src/usus.js b/src/usus.js index ef4ca4e..27a33a6 100644 --- a/src/usus.js +++ b/src/usus.js @@ -150,6 +150,14 @@ export const render = async (url: string, userConfiguration: UserConfigurationTy }); } + const inlineStylesheetIndex = []; + + CSS.styleSheetAdded(({header}) => { + if (header.isInline) { + inlineStylesheetIndex.push(header.styleSheetId); + } + }); + CSS.startRuleUsageTracking(); Page.navigate({ @@ -164,6 +172,8 @@ export const render = async (url: string, userConfiguration: UserConfigurationTy await delay(configuration.delay); + debug('inline stylesheets', inlineStylesheetIndex); + const rules = await CSS.takeCoverageDelta(); const usedRules = rules.coverage @@ -174,6 +184,13 @@ export const render = async (url: string, userConfiguration: UserConfigurationTy const slices = []; for (const usedRule of usedRules) { + if (inlineStylesheetIndex.includes(usedRule.styleSheetId)) { + debug('skipping inline stylesheet %d', usedRule.styleSheetId); + + // eslint-disable-next-line no-continue + continue; + } + const stylesheet = await CSS.getStyleSheetText({ styleSheetId: usedRule.styleSheetId }); @@ -220,7 +237,10 @@ export const render = async (url: string, userConfiguration: UserConfigurationTy await inlineStylePreload(DOM, Runtime, rootDocument.root.nodeId, styleImportLinks); } - await inlineStyles(DOM, Runtime, rootDocument.root.nodeId, usedStyles); + if (usedStyles) { + await inlineStyles(DOM, Runtime, rootDocument.root.nodeId, usedStyles); + } + await inlineImports(DOM, Runtime, rootDocument.root.nodeId, styleImportLinks); const rootOuterHTMLWithInlinedStyles = (await DOM.getOuterHTML({ @@ -235,6 +255,8 @@ export const render = async (url: string, userConfiguration: UserConfigurationTy if (configuration.extractStyles) { await chrome.kill(); + // @todo Document that `extractStyles` does not return inline stylesheets. + return usedStyles; } diff --git a/test/usus.js b/test/usus.js index 07eb50d..789829d 100644 --- a/test/usus.js +++ b/test/usus.js @@ -145,6 +145,46 @@ test('extracts CSS', async (t) => { t.true(result.replace(/\s/g, '') === 'body{background:#f00;}'); }); +test('does not re-inline the inline CSS', async (t) => { + const server = await serve(` + + + + + +

Hello, World!

+ + + `); + + const result = await render(server.url, { + delay: 500, + inlineStyles: true, + preloadStyles: false + }); + + await server.close(); + + t.true(isHtmlEqual(result, ` + + + + + +

Hello, World!

+ + + `)); +}); + test('extracts only the used CSS', async (t) => { const styleServer = await serve(` body {