Last active
March 17, 2024 14:14
-
-
Save mootari/333cca8cf708ad886a790e55034fe291 to your computer and use it in GitHub Desktop.
Content Snippet that bundles the current page's stylesheets and assets into a zip file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(async()=>{ | |
const customCss = ` | |
#title-heading {clear:left} | |
`; | |
const asyncArray = (iter, map) => Promise.all(Array.from(iter, map)); | |
const css = (await asyncArray( | |
document.querySelectorAll('link[rel="stylesheet"][href^="/"]'), | |
async n => (await fetch(n.href, {mode: 'no-cors'})).text() | |
)).join("\n").replace(/\/\*.*?\*\//gs, ''); | |
const paths = new Map(); | |
const pattern = /\burl\((['"]?)(?<url>\/.*?)(?<hash>#.*?)?\1\)/g; | |
const rewritten = css.replace(pattern, (str, quote, url, hash = '') => { | |
const name = url.split('?', 2)[0].split('/').at(-1); | |
if(!paths.has(url)) paths.set(url, `./assets/file-${paths.size}-${name}`); | |
return `url("${paths.get(url)}${hash}")`; | |
}); | |
console.log(`Fetching ${paths.size} files ...`); | |
const files = Object.fromEntries([ | |
['./site.css', new TextEncoder().encode(rewritten + customCss)], | |
...await asyncArray( | |
paths, | |
async ([url, local]) => [local, new Uint8Array(await (await fetch(url)).arrayBuffer())] | |
) | |
]); | |
// Note: CSPs may prevent the module from loading. | |
const {zipSync} = await import('https://cdn.jsdelivr.net/npm/[email protected]/+esm'); | |
console.log('Generating archive ...'); | |
const archive = zipSync(files, {level: 9}); | |
const a = document.createElement('a'); | |
a.download = 'styles.zip'; | |
a.href = URL.createObjectURL(new Blob([archive])); | |
a.click(); | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Joshua-Beatty-Pearagon Thanks! Do you happen to have a public link where this change can be tested?