Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Adopted stylesheets benchmark
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Adopted stylesheets benchmark</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
pre {
position: fixed;
right: 0;
top: 0;
padding: 20px;
background: rgba(30, 30, 30, 0.8);
color: white;
pointer-events: none;
}
</style>
</head>
<body>
<h1>Adopted stylesheets benchmark</h1>
<pre></pre>
<script type="module">
function createSheet(css) {
const sheet = new CSSStyleSheet()
sheet.replaceSync(css)
return sheet
}
const duplicateSheet = createSheet(`.foo { color: red }`)
const duplicateSheets = Array(1000).fill().map(() => duplicateSheet)
const uniqueSheets = Array(1000).fill().map((_, i) => `.foo-${i} { color: red }`).map(createSheet)
const sheets = [...duplicateSheets, ...uniqueSheets]
const params = new URLSearchParams(location.search)
const mode = params.get('mode')
if (mode === 'buffered') {
document.querySelector('h1').textContent += ' (buffered mode)'
} else if (mode === 'duplicates') {
document.querySelector('h1').textContent += ' (duplicates mode)'
}
performance.mark('start')
if (mode === 'buffered') {
const existing = new Set([...document.adoptedStyleSheets])
const sheetsToAdd = sheets.filter((stylesheet) => {
if (existing.has(stylesheet)) {
return false;
}
existing.add(stylesheet);
return true;
});
document.adoptedStyleSheets = [...document.adoptedStyleSheets, ...sheetsToAdd]
} else if (mode === 'duplicates') {
for (const sheet of sheets) {
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet]
}
} else {
for (const sheet of sheets) {
if (!document.adoptedStyleSheets.includes(sheet)) {
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet]
}
}
}
performance.measure('total', 'start')
const { duration } = performance.getEntriesByName('total')[0]
document.querySelector('pre').textContent = `Took ${duration} ms`
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment