Skip to content

Instantly share code, notes, and snippets.

@kafene
Created March 7, 2020 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kafene/5e79bfaf846dc8483b1c49ad97e6d66f to your computer and use it in GitHub Desktop.
Save kafene/5e79bfaf846dc8483b1c49ad97e6d66f to your computer and use it in GitHub Desktop.
Refresh / reload CSS bookmarklet
javascript:(function () {
const now = Date.now().toFixed(2);
/* Append timestamp to all linked stylesheet urls */
for (const link of document.querySelectorAll('link[rel~="stylesheet"][href]')) {
const url = new URL(link.href);
url.searchParams.set('_cssrefresh', now);
link.href = url.href;
}
for (const style of document.querySelectorAll('style')) {
let css = style.innerHTML;
/* Append timestamp to all @import-ed stylesheet urls */
css = css.replace(/@import\s+?url\s*\(\s*(.+?)\s*\)\s*;/mg, function (m, url) {
let oldUrl = url, newUrl = url, quote = '';
if (url.startsWith("'") && url.endsWith("'")) {
newUrl = url.slice(1, -1), quote = "'";
} else if (url.startsWith('"') && url.endsWith('"')) {
newUrl = url.slice(1, -1), quote = '"';
}
try {
newUrl = new URL(newUrl);
newUrl.searchParams.set('_cssrefresh', now);
newUrl = quote + newUrl.href + quote;
return m.replace(oldUrl, newUrl);
} catch (e) {}
try {
newUrl = newUrl.replace(/[?&]_cssrefresh=([^&$]*)/, '');
let qs = newUrl.indexOf('?') >= 0 ? '&' : '?';
newUrl += `${qs}_cssrefresh=${now}`;
newUrl = quote + newUrl + quote;
return m.replace(oldUrl, newUrl);
} catch (e) {}
return m;
});
/* Append timestamp to end of stylesheet contents */
const reRefresh = /\n\/\* _cssrefresh=(.+?) \*\/\n/mg;
if (reRefresh.test(css)) {
css = css.replace(reRefresh, function (m, then) {
return `\n/* _cssrefresh=${now} */\n`;
});
} else {
css += `\n/* _cssrefresh=${now} */\n`;
}
style.innerHTML = css;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment