From fd388d04759f2b092283af2e0786672f08357bf1 Mon Sep 17 00:00:00 2001 From: neverland Date: Tue, 16 Jun 2020 22:59:07 +0800 Subject: [PATCH] perf: use inline style instead of getComputedStyle (#6550) --- src/utils/format/unit.ts | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/utils/format/unit.ts b/src/utils/format/unit.ts index 7f422c6af..b50167e7c 100644 --- a/src/utils/format/unit.ts +++ b/src/utils/format/unit.ts @@ -10,13 +10,24 @@ export function addUnit(value?: string | number): string | undefined { return isNumeric(value) ? `${value}px` : value; } +// cache +let rootFontSize: number; + +function getRootFontSize() { + if (!rootFontSize) { + const doc = document.documentElement; + const fontSize = + doc.style.fontSize || window.getComputedStyle(doc).fontSize; + + rootFontSize = parseFloat(fontSize); + } + + return rootFontSize; +} + function convertRem(value: string) { - const rootStyle = window.getComputedStyle(document.documentElement); - const rootFontSize = parseFloat(rootStyle.fontSize); - value = value.replace(/rem/g, ''); - - return +value * rootFontSize; + return +value * getRootFontSize(); } export function unitToPx(value: string | number): number {