Skip to content

Instantly share code, notes, and snippets.

@mootari
Last active March 17, 2024 14:14
Show Gist options
  • Save mootari/333cca8cf708ad886a790e55034fe291 to your computer and use it in GitHub Desktop.
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.
(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();
})()
@Ihyun
Copy link

Ihyun commented Mar 10, 2022

@Joshua-Beatty-Pearagon, your code does not work. @mootari 's code works. Thanks all!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment