perf(assets): reduce HTTP requests to CDN

This commit is contained in:
Cotes Chung 2023-03-23 01:29:17 +08:00
parent 016a9baddd
commit 9d97120197
No known key found for this signature in database
GPG key ID: 0D9E54843167A808
9 changed files with 167 additions and 139 deletions

View file

@ -1,44 +1,54 @@
<!-- https://giscus.app/ --> <!-- https://giscus.app/ -->
<script type="text/javascript"> <script type="text/javascript">
$(function () { (function () {
const origin = "https://giscus.app"; const origin = 'https://giscus.app';
const iframe = "iframe.giscus-frame"; const iframe = 'iframe.giscus-frame';
const lightTheme = "light"; const lightTheme = 'light';
const darkTheme = "dark_dimmed"; const darkTheme = 'dark_dimmed';
let initTheme = lightTheme;
if ($("html[data-mode=dark]").length > 0 let initTheme = lightTheme;
|| ($("html[data-mode]").length == 0 const html = document.documentElement;
&& window.matchMedia("(prefers-color-scheme: dark)").matches)) {
if (
(html.hasAttribute('data-mode') &&
html.getAttribute('data-mode') === 'dark') ||
(!html.hasAttribute('data-mode') &&
window.matchMedia('(prefers-color-scheme: dark)').matches)
) {
initTheme = darkTheme; initTheme = darkTheme;
} }
let giscusAttributes = { let giscusAttributes = {
"src": "https://giscus.app/client.js", src: 'https://giscus.app/client.js',
"data-repo": "{{ site.comments.giscus.repo}}", 'data-repo': '{{ site.comments.giscus.repo}}',
"data-repo-id": "{{ site.comments.giscus.repo_id }}", 'data-repo-id': '{{ site.comments.giscus.repo_id }}',
"data-category": "{{ site.comments.giscus.category }}", 'data-category': '{{ site.comments.giscus.category }}',
"data-category-id": "{{ site.comments.giscus.category_id }}", 'data-category-id': '{{ site.comments.giscus.category_id }}',
"data-mapping": "{{ site.comments.giscus.mapping | default: 'pathname' }}", 'data-mapping': '{{ site.comments.giscus.mapping | default: 'pathname' }}',
"data-reactions-enabled": "{{ site.comments.giscus.reactions_enabled | default: '1' }}", 'data-reactions-enabled': '{{ site.comments.giscus.reactions_enabled | default: '1' }}',
"data-emit-metadata": "0", 'data-emit-metadata': '0',
"data-theme": initTheme, 'data-theme': initTheme,
"data-input-position": "{{ site.comments.giscus.input_position | default: 'bottom' }}", 'data-input-position': '{{ site.comments.giscus.input_position | default: 'bottom' }}',
"data-lang": "{{ site.comments.giscus.lang | default: lang }}", 'data-lang': '{{ site.comments.giscus.lang | default: lang }}',
"crossorigin": "anonymous", crossorigin: 'anonymous',
"async": "" async: ''
}; };
let giscusScript = document.createElement("script"); let giscusScript = document.createElement('script');
Object.entries(giscusAttributes).forEach(([key, value]) => giscusScript.setAttribute(key, value)); Object.entries(giscusAttributes).forEach(([key, value]) =>
document.getElementById("tail-wrapper").appendChild(giscusScript); giscusScript.setAttribute(key, value)
);
document.getElementById('tail-wrapper').appendChild(giscusScript);
addEventListener("message", (event) => { addEventListener('message', (event) => {
if (event.source === window && event.data && if (
event.data.direction === ModeToggle.ID) { event.source === window &&
event.data &&
event.data.direction === ModeToggle.ID
) {
/* global theme mode changed */ /* global theme mode changed */
const mode = event.data.message; const mode = event.data.message;
const theme = (mode === ModeToggle.DARK_MODE ? darkTheme : lightTheme); const theme = mode === ModeToggle.DARK_MODE ? darkTheme : lightTheme;
const message = { const message = {
setConfig: { setConfig: {
@ -49,8 +59,6 @@
const giscus = document.querySelector(iframe).contentWindow; const giscus = document.querySelector(iframe).contentWindow;
giscus.postMessage({ giscus: message }, origin); giscus.postMessage({ giscus: message }, origin);
} }
});
}); });
})();
</script> </script>

View file

@ -108,8 +108,6 @@
<!-- JavaScript --> <!-- JavaScript -->
<script src="{{ site.data.assets[origin].jquery.js | relative_url }}"></script>
{% unless site.theme_mode %} {% unless site.theme_mode %}
{% include mode-toggle.html %} {% include mode-toggle.html %}
{% endunless %} {% endunless %}

View file

@ -1,27 +1,35 @@
<!-- JS selector for site. --> <!-- JS selector for site. -->
<!-- commons -->
{% assign urls = site.data.assets[origin].jquery.js
| append: ','
| append: site.data.assets[origin].bootstrap.js
| append: ','
| append: site.data.assets[origin].search.js
%}
<!-- layout specified --> <!-- layout specified -->
{% if page.layout == 'post' %} {% if page.layout == 'post' %}
{% if site.google_analytics.pv.proxy_endpoint or site.google_analytics.pv.cache_path %} {% if site.google_analytics.pv.proxy_endpoint or site.google_analytics.pv.cache_path %}
<!-- pv-report needs countup.js --> <!-- pv-report needs countup.js -->
<script async src="{{ site.data.assets[origin].countup.js | relative_url }}"></script> {% assign urls = urls | append: ',' | append: site.data.assets[origin].countup.js %}
{% endif %} {% endif %}
{% endif %} {% endif %}
{% if page.layout == 'post' or page.layout == 'page' or page.layout == 'home' %} {% if page.layout == 'post' or page.layout == 'page' or page.layout == 'home' %}
{% assign _urls = site.data.assets[origin].lazysizes.js %} {% assign urls = urls | append: ',' | append: site.data.assets[origin].lazysizes.js %}
{% unless page.layout == 'home' %} {% unless page.layout == 'home' %}
{% assign _urls = _urls <!-- image lazy-loading & popup & clipboard -->
{% assign urls = urls
| append: ',' | append: ','
| append: site.data.assets[origin]['magnific-popup'].js | append: site.data.assets[origin]['magnific-popup'].js
| append: ',' | append: ','
| append: site.data.assets[origin].clipboard.js | append: site.data.assets[origin].clipboard.js
%} %}
{% endunless %} {% endunless %}
{% include jsdelivr-combine.html urls=_urls %}
{% endif %} {% endif %}
{% if page.layout == 'home' {% if page.layout == 'home'
@ -32,7 +40,9 @@
%} %}
{% assign locale = site.lang | split: '-' | first %} {% assign locale = site.lang | split: '-' | first %}
{% assign _urls = site.data.assets[origin].dayjs.js.common {% assign urls = urls
| append: ','
| append: site.data.assets[origin].dayjs.js.common
| append: ',' | append: ','
| append: site.data.assets[origin].dayjs.js.locale | append: site.data.assets[origin].dayjs.js.locale
| replace: ':LOCALE', locale | replace: ':LOCALE', locale
@ -41,10 +51,18 @@
| append: ',' | append: ','
| append: site.data.assets[origin].dayjs.js.localizedFormat | append: site.data.assets[origin].dayjs.js.localizedFormat
%} %}
{% include jsdelivr-combine.html urls=_urls %}
{% endif %} {% endif %}
{% if page.content contains '<h2' or page.content contains '<h3' and site.toc and page.toc %}
{% assign urls = urls | append: ',' | append: site.data.assets[origin].toc.js %}
{% endif %}
{% if page.mermaid %}
{% assign urls = urls | append: ',' | append: site.data.assets[origin].mermaid.js %}
{% endif %}
{% include jsdelivr-combine.html urls=urls %}
{% case page.layout %} {% case page.layout %}
{% when 'home', 'categories', 'post', 'page' %} {% when 'home', 'categories', 'post', 'page' %}
{% assign type = page.layout %} {% assign type = page.layout %}
@ -80,10 +98,6 @@
<script id="MathJax-script" async src="{{ site.data.assets[origin].mathjax.js | relative_url }}"></script> <script id="MathJax-script" async src="{{ site.data.assets[origin].mathjax.js | relative_url }}"></script>
{% endif %} {% endif %}
<!-- commons -->
<script src="{{ site.data.assets[origin].bootstrap.js | relative_url }}"></script>
{% if jekyll.environment == 'production' %} {% if jekyll.environment == 'production' %}
<!-- PWA --> <!-- PWA -->
{% if site.pwa.enabled %} {% if site.pwa.enabled %}

View file

@ -5,7 +5,6 @@
{% assign domain = 'https://cdn.jsdelivr.net/' %} {% assign domain = 'https://cdn.jsdelivr.net/' %}
{% for url in urls %} {% for url in urls %}
{% if url contains domain %} {% if url contains domain %}
{% assign url_snippet = url | slice: domain.size, url.size %} {% assign url_snippet = url | slice: domain.size, url.size %}
@ -16,15 +15,10 @@
{% endif %} {% endif %}
{% elsif url contains '//' %} {% elsif url contains '//' %}
<script src="{{ url }}"></script> <script src="{{ url }}"></script>
{% else %} {% else %}
<script src="{{ url | relative_url }}"></script> <script src="{{ url | relative_url }}"></script>
{% endif %} {% endif %}
{% endfor %} {% endfor %}
{% if combined_urls %} {% if combined_urls %}

View file

@ -1,43 +1,37 @@
<!-- <!-- mermaid-js loader -->
mermaid-js loader <script type="text/javascript">
-->
<script src="{{ site.data.assets[origin].mermaid.js | relative_url }}"></script>
<script>
(function () { (function () {
function updateMermaid(event) { function updateMermaid(event) {
if (event.source === window && event.data && if (event.source === window && event.data && event.data.direction === ModeToggle.ID) {
event.data.direction === ModeToggle.ID) {
const mode = event.data.message; const mode = event.data.message;
if (typeof mermaid === "undefined") { if (typeof mermaid === 'undefined') {
return; return;
} }
let expectedTheme = (mode === ModeToggle.DARK_MODE ? "dark" : "default"); let expectedTheme = mode === ModeToggle.DARK_MODE ? 'dark' : 'default';
let config = {theme: expectedTheme}; let config = { theme: expectedTheme };
/* Re-render the SVG <https://github.com/mermaid-js/mermaid/issues/311#issuecomment-332557344> */ /* Re-render the SVG <https://github.com/mermaid-js/mermaid/issues/311#issuecomment-332557344> */
$(".mermaid").each(function () { $('.mermaid').each(function () {
let svgCode = $(this).prev().children().html(); let svgCode = $(this).prev().children().html();
$(this).removeAttr("data-processed"); $(this).removeAttr('data-processed');
$(this).html(svgCode); $(this).html(svgCode);
}); });
mermaid.initialize(config); mermaid.initialize(config);
mermaid.init(undefined, ".mermaid"); mermaid.init(undefined, '.mermaid');
} }
} }
let initTheme = "default"; let initTheme = 'default';
const html = document.documentElement;
if ($("html[data-mode=dark]").length > 0 if (
|| ($("html[data-mode]").length == 0 (html.hasAttribute('data-mode') && html.getAttribute('data-mode') === 'dark') ||
&& window.matchMedia("(prefers-color-scheme: dark)").matches)) { (!html.hasAttribute('data-mode') && window.matchMedia('(prefers-color-scheme: dark)').matches)
initTheme = "dark"; ) {
initTheme = 'dark';
} }
let mermaidConf = { let mermaidConf = {
@ -45,15 +39,20 @@
}; };
/* Create mermaid tag */ /* Create mermaid tag */
$("pre").has("code.language-mermaid").each(function () { document.querySelectorAll('pre>code.language-mermaid').forEach((elem) => {
let svgCode = $(this).children().html(); const svgCode = elem.textContent;
$(this).addClass("unloaded"); const backup = elem.parentElement;
$(this).after(`<pre class=\"mermaid\">${svgCode}</pre>`); backup.classList.add('unloaded');
/* create mermaid node */
let mermaid = document.createElement('pre');
mermaid.classList.add('mermaid');
const text = document.createTextNode(svgCode);
mermaid.appendChild(text);
backup.after(mermaid);
}); });
mermaid.initialize(mermaidConf); mermaid.initialize(mermaidConf);
window.addEventListener("message", updateMermaid); window.addEventListener('message', updateMermaid);
})(); })();
</script> </script>

View file

@ -1,14 +1,22 @@
<!-- <!-- Switch the mode between dark and light. -->
Switch the mode between dark and light.
-->
<script type="text/javascript"> <script type="text/javascript">
class ModeToggle { class ModeToggle {
static get MODE_KEY() { return "mode"; } static get MODE_KEY() {
static get MODE_ATTR() { return "data-mode"; } return 'mode';
static get DARK_MODE() { return "dark"; } }
static get LIGHT_MODE() { return "light"; } static get MODE_ATTR() {
static get ID() { return "mode-toggle"; } return 'data-mode';
}
static get DARK_MODE() {
return 'dark';
}
static get LIGHT_MODE() {
return 'light';
}
static get ID() {
return 'mode-toggle';
}
constructor() { constructor() {
if (this.hasMode) { if (this.hasMode) {
@ -45,17 +53,29 @@
}); });
} /* constructor() */ } /* constructor() */
get sysDarkPrefers() { return window.matchMedia("(prefers-color-scheme: dark)"); } get sysDarkPrefers() {
return window.matchMedia('(prefers-color-scheme: dark)');
}
get isSysDarkPrefer() { return this.sysDarkPrefers.matches; } get isSysDarkPrefer() {
return this.sysDarkPrefers.matches;
}
get isDarkMode() { return this.mode === ModeToggle.DARK_MODE; } get isDarkMode() {
return this.mode === ModeToggle.DARK_MODE;
}
get isLightMode() { return this.mode === ModeToggle.LIGHT_MODE; } get isLightMode() {
return this.mode === ModeToggle.LIGHT_MODE;
}
get hasMode() { return this.mode != null; } get hasMode() {
return this.mode != null;
}
get mode() { return sessionStorage.getItem(ModeToggle.MODE_KEY); } get mode() {
return sessionStorage.getItem(ModeToggle.MODE_KEY);
}
/* get the current mode on screen */ /* get the current mode on screen */
get modeStatus() { get modeStatus() {
@ -67,26 +87,29 @@
} }
setDark() { setDark() {
$('html').attr(ModeToggle.MODE_ATTR, ModeToggle.DARK_MODE); document.documentElement.setAttribute(ModeToggle.MODE_ATTR, ModeToggle.DARK_MODE);
sessionStorage.setItem(ModeToggle.MODE_KEY, ModeToggle.DARK_MODE); sessionStorage.setItem(ModeToggle.MODE_KEY, ModeToggle.DARK_MODE);
} }
setLight() { setLight() {
$('html').attr(ModeToggle.MODE_ATTR, ModeToggle.LIGHT_MODE); document.documentElement.setAttribute(ModeToggle.MODE_ATTR, ModeToggle.LIGHT_MODE);
sessionStorage.setItem(ModeToggle.MODE_KEY, ModeToggle.LIGHT_MODE); sessionStorage.setItem(ModeToggle.MODE_KEY, ModeToggle.LIGHT_MODE);
} }
clearMode() { clearMode() {
$('html').removeAttr(ModeToggle.MODE_ATTR); document.documentElement.removeAttribute(ModeToggle.MODE_ATTR);
sessionStorage.removeItem(ModeToggle.MODE_KEY); sessionStorage.removeItem(ModeToggle.MODE_KEY);
} }
/* Notify another plugins that the theme mode has changed */ /* Notify another plugins that the theme mode has changed */
notify() { notify() {
window.postMessage({ window.postMessage(
{
direction: ModeToggle.ID, direction: ModeToggle.ID,
message: this.modeStatus message: this.modeStatus
}, "*"); },
'*'
);
} }
flipMode() { flipMode() {

View file

@ -16,11 +16,9 @@
{% capture not_found %}<p class="mt-5">{{ site.data.locales[include.lang].search.no_results }}</p>{% endcapture %} {% capture not_found %}<p class="mt-5">{{ site.data.locales[include.lang].search.no_results }}</p>{% endcapture %}
<script src="{{ site.data.assets[origin].search.js | relative_url }}"></script>
<script> <script>
/* Note: dependent library will be loaded in `js-selector.html` */
SimpleJekyllSearch({ SimpleJekyllSearch({
searchInput: document.getElementById('search-input'), searchInput: document.getElementById('search-input'),
resultsContainer: document.getElementById('search-results'), resultsContainer: document.getElementById('search-results'),
json: '{{ '/assets/js/data/search.json' | relative_url }}', json: '{{ '/assets/js/data/search.json' | relative_url }}',
@ -43,6 +41,5 @@ SimpleJekyllSearch({
} }
} }
} }
}); });
</script> </script>

View file

@ -10,7 +10,4 @@
<div class="panel-heading ps-3 pt-2 mb-2">{{- site.data.locales[include.lang].panel.toc -}}</div> <div class="panel-heading ps-3 pt-2 mb-2">{{- site.data.locales[include.lang].panel.toc -}}</div>
<nav id="toc"></nav> <nav id="toc"></nav>
</div> </div>
<!-- toc.js will be loaded at medium priority -->
<script src="{{ site.data.assets[origin].toc.js | relative_url }}"></script>
{% endif %} {% endif %}

View file

@ -21,7 +21,6 @@ layout: compress
<body data-topbar-visible="true"> <body data-topbar-visible="true">
{% include sidebar.html lang=lang %} {% include sidebar.html lang=lang %}
{% include topbar.html lang=lang %} {% include topbar.html lang=lang %}
<div id="main-wrapper" class="d-flex justify-content-center"> <div id="main-wrapper" class="d-flex justify-content-center">
@ -31,14 +30,9 @@ layout: compress
{% include search-results.html lang=lang %} {% include search-results.html lang=lang %}
</div> </div>
<!-- #main-wrapper -->
{% include footer.html lang=lang %} {% include footer.html lang=lang %}
{% if page.mermaid %}
{% include mermaid.html %}
{% endif %}
<div id="mask"></div> <div id="mask"></div>
<a id="back-to-top" href="#" aria-label="back-to-top" class="btn btn-lg btn-box-shadow" role="button"> <a id="back-to-top" href="#" aria-label="back-to-top" class="btn btn-lg btn-box-shadow" role="button">
@ -72,8 +66,12 @@ layout: compress
</div> </div>
{% endif %} {% endif %}
{% include search-loader.html %}
{% include js-selector.html %} {% include js-selector.html %}
{% if page.mermaid %}
{% include mermaid.html %}
{% endif %}
{% include search-loader.html %}
</body> </body>
</html> </html>