博客搭建与魔改系列教程导航🚥🚥🚥

阅读约定:每个代码块上方都标了 文件 和 改法。[Blogroot] 指博客根目录;「新建」是建文件后整段写入,「追加」是放到文件末尾,「替换 / 放在某函数里」是在已有文件里改对应位置。标「关键段」的代码是拆解说明,完整文件按同目录的实际文件对照补齐。

这十节分别改哪里
  • 51:首页多栏卡片,三栏 / 双栏与五边形封面
  • 52:侧栏「欢迎来访」与「倒计时」
  • 53:网站信息卡移到列表底部横排
  • 54:画廊分类大厅与瀑布流
  • 55:旧时光按年份分类与跳转
  • 56:公告卡改造与手机侧边菜单入口
  • 57:Cookie 同意与第三方服务门控
  • 58:Service Worker 静态资源缓存
  • 59:图片、字体与前端资源的瘦身
  • 60:订阅源 BOM 与 custom.css 截断修复

路径统一用 [Blogroot] 表示博客根目录。自定义样式放在 [Blogroot]/source/css/,脚本放在 [Blogroot]/source/js/,构建脚本放在 [Blogroot]/scripts/,不改主题源码。

51. 首页多栏:三栏卡片与五边形封面

Butterfly 5.x 的首页列表多了一层 .recent-post-items 包裹,旧版直接写 #recent-posts > .recent-post-item 的双栏样式会全部失配。重写时干脆换个思路:把多栏做成开关,只有 <html> 带 hg-article-multi 时才生效。

先在 _config.yml 里加一个站点级开关:

文件:[Blogroot]/_config.yml | 改法:在文件末尾追加这两行;如果已有同名配置,直接改原值。

1
2
3
# 首页文章多栏:true 时默认三栏,中屏自动两栏
butterfly_article_double_row:
enable: true

构建期给 <html> 加类,并记住默认值,供美化设置里的「恢复默认」使用:

文件:[Blogroot]/scripts/article-layout.js | 改法:新建文件,整段写入;scripts 目录不存在就自己在博客根目录建一个。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* [Blogroot]\scripts\article-layout.js */
'use strict';

const on = (() => {
const cfg = hexo.config.butterfly_article_double_row || {};
return cfg.enable === true || cfg.enable === 'true' || cfg.enable === 1;
})();

hexo.extend.filter.register('after_render:html', function (html) {
return html.replace(/<html\b([^>]*)>/, (match, attrs) => {
const flag = ' data-article-default="' + (on ? '1' : '0') + '"';
if (!on) return '<html' + attrs + flag + '>';
if (/class=(["'])/.test(attrs)) {
attrs = attrs.replace(/class=(["'])(.*?)\1/, (m, q, list) => 'class="' + list + ' hg-article-multi"');
return '<html' + attrs + flag + '>';
}
return '<html' + attrs + ' class="hg-article-multi"' + flag + '>';
});
});

为什么用构建期加类,而不是直接在模板里写死?因为美化设置面板要能实时切换多栏,类挂在 <html> 上最方便;而 data-article-default 保存构建默认值,用户点「恢复默认」时能回到配置里的状态,不会和面板的临时选择打架。

CSS 的核心是容器改 Flex,卡片固定「封面 200px + 信息 150px」:

文件:[Blogroot]/source/css/custom.css | 改法:追加到文件末尾。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
html.hg-article-multi #recent-posts > .recent-post-items {
display: flex;
flex-wrap: wrap;
align-content: flex-start;
width: 100%;
padding: 0 5px;
}

html.hg-article-multi #recent-posts > .recent-post-items > .recent-post-item {
position: relative;
display: flex;
flex-direction: column;
height: auto !important;
max-height: 350px;
margin: 0 0 20px;
border-radius: 15px;
overflow: hidden;
}

五边形封面靠 clip-path,底部留一个尖角:

文件:[Blogroot]/source/css/custom.css | 改法:紧接上一段样式追加,仍放在多栏样式区域内。

1
2
3
4
5
6
7
8
html.hg-article-multi #recent-posts > .recent-post-items > .recent-post-item > .post_cover {
order: 0 !important;
width: 100% !important;
height: 200px !important;
flex: 0 0 200px;
clip-path: polygon(0 130px, 0 0, 100% 0, 100% 130px, 50% 100%);
overflow: hidden;
}

摘要不是挂在信息区下面,而是绝对定位压回封面上,形成一层半透明遮罩:

文件:[Blogroot]/source/css/custom.css | 改法:紧接上一段样式追加。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
html.hg-article-multi .recent-post-item > .recent-post-info > .content {
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 200px;
margin: 0 !important;
padding: 0 !important;
overflow: hidden;
background: rgba(25, 25, 25, .4);
clip-path: polygon(0 130px, 0 0, 100% 0, 100% 130px, 50% 100%);
pointer-events: none;
}

html.hg-article-multi .recent-post-item > .recent-post-info > .content > .content-text {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
margin: 0 25px 30px;
color: #fff;
font-size: 16px;
line-height: 1.6;
text-align: center;
text-shadow: 1px 2px 3px #000;
}

这里有个容易翻车的点:截断必须放在内层 .content-text 上。摘要外层是绝对定位元素,Chrome 会把它块级化为 flow-root,-webkit-box 的截断随之失效;把 -webkit-line-clamp 放到真正包文字的内层才有效。

宽度和分页器:

文件:[Blogroot]/source/css/custom.css | 改法:追加到多栏样式末尾,分页器规则不要漏。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@media screen and (min-width: 1069px) {
html.hg-article-multi .recent-post-item {
width: 32.3%;
margin: 0 1% 20px 0;
}
}

@media screen and (min-width: 573px) and (max-width: 1068px) {
html.hg-article-multi .recent-post-item {
width: 47%;
margin: 0 3% 20px 0;
}
}

/* 分页器必须独占整行,否则会被塞进卡片缝隙 */
html.hg-article-multi #recent-posts > .recent-post-items > .pagination,
html.hg-article-multi #recent-posts > .recent-post-items > #pagination,
html.hg-article-multi #recent-posts > .recent-post-items > nav {
width: 100%;
flex: 0 0 100%;
}

三栏时每页文章数最好取 3 的倍数,本站用 12 篇,正好铺满四行。注意手机宽度下不加多栏,保持主题原来的单列,否则摘要叠层会把小屏挤爆。

52. 侧栏:欢迎来访与倒计时

这两张卡只在首页出现,挂在侧栏 .sticky_layout 里、个人信息卡后面。脚本先判断首页标志 #recent-posts,避免在文章页和独立页面误插:

文件:[Blogroot]/source/js/fomal/welcome-card.js | 改法:新建文件;完整源码可打开本站 /js/fomal/welcome-card.js 对照,下面先拆 mount() 关键段。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* [Blogroot]\source\js\fomal\welcome-card.js 节选 */
function mount () {
if (!d.getElementById('recent-posts')) return
var sticky = d.querySelector('#aside-content .sticky_layout')
if (!sticky) return
if (d.getElementById('hg-welcome-greet')) return

var info = sticky.querySelector('.card-info')
if (info) info.insertAdjacentHTML('afterend', welcomeHTML() + countdownHTML())
else sticky.insertAdjacentHTML('afterbegin', welcomeHTML() + countdownHTML())

setPoem()
loadGeo()
tick()
if (timer) w.clearInterval(timer)
timer = w.setInterval(tick, 60000)
}

问候语按小时切换,诗句从本地数组随机抽,避免连续两次抽到同一句:

文件:[Blogroot]/source/js/fomal/welcome-card.js | 改法:放在 randomPoem() 函数里,替换同名逻辑。

1
2
3
4
5
6
7
var lastPoem = -1
function randomPoem () {
var i = Math.floor(Math.random() * POEMS.length)
if (i === lastPoem && POEMS.length > 1) i = (i + 1) % POEMS.length
lastPoem = i
return POEMS[i]
}

倒计时全部用本地时间算,不发请求。今日、本周、本月、本年四条进度各自算百分比和剩余量:

文件:[Blogroot]/source/js/fomal/welcome-card.js | 改法:放在 pctRows() 函数里;今日、本周、本月、本年的计算都在这一个函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function pctRows (now) {
var day = (now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds()) / 86400
var weekDay = (now.getDay() + 6) % 7
var week = (weekDay + day) / 7
var daysInMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate()
var month = (now.getDate() - 1 + day) / daysInMonth
var daysInYear = ((now.getFullYear() % 4 === 0 && now.getFullYear() % 100 !== 0) || now.getFullYear() % 400 === 0) ? 366 : 365
var year = (dayOfYear(now) - 1 + day) / daysInYear
return [
{ pct: day, left: '剩 ' + Math.ceil(24 - now.getHours() - now.getMinutes() / 60) + ' 小时' },
{ pct: week, left: '剩 ' + (7 - weekDay) + ' 天' },
{ pct: month, left: '剩 ' + (daysInMonth - now.getDate() + 1) + ' 天' },
{ pct: year, left: '剩 ' + (daysInYear - dayOfYear(now) + 1) + ' 天' }
]
}

来访地区属于第三方请求,必须受 Cookie 同意门控。没同意时只显示「地区显示未开启」,点一下还能打开 Cookie 设置:

文件:[Blogroot]/source/js/fomal/welcome-card.js | 改法:替换 loadGeo() 前半段;后面的接口请求与缓存保持原样。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function loadGeo () {
if (geoLoaded) return
var allowed = w.hgConsent && w.hgConsent.granted ? w.hgConsent.granted('analytics') : false
if (!allowed) {
setRegion('地区显示未开启', '距离信息未开启')
var hint = $('hg-welcome-region')
if (hint) {
hint.title = '在 Cookie 设置中允许访问统计后显示'
hint.style.cursor = 'pointer'
hint.onclick = function () { if (w.hgOpenConsent) w.hgOpenConsent() }
}
return
}
// 主接口 api.ipapi.is,失败回退 ipwho.is;结果在 sessionStorage 缓存 6 小时
}

距离用 Haversine 公式按本站坐标估算。本站坐标是桂林,改代码时记得换成自己的经纬度:

文件:[Blogroot]/source/js/fomal/welcome-card.js | 改法:改文件顶部的 HOME 常量,换成你所在城市的经纬度。

1
var HOME = { lat: 25.2802, lng: 110.2964, name: '桂林' }

最后是 pjax 生命周期。pjax 往返会换掉整个侧栏,所以要清定时器、删旧卡片、重建:

文件:[Blogroot]/source/js/fomal/welcome-card.js | 改法:用这两段替换文件末尾的 unmount() / refresh(),并保留 hg-consent-change 监听。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function unmount () {
if (timer) { w.clearInterval(timer); timer = null }
}

function refresh () {
unmount()
geoLoaded = false
var old = d.querySelectorAll('.hg-welcome-card, .hg-countdown-card')
for (var i = 0; i < old.length; i++) {
if (old[i].parentNode) old[i].parentNode.removeChild(old[i])
}
mount()
}

document.addEventListener('hg-consent-change', function (event) {
var state = event.detail || {}
geoLoaded = false
if (state.analytics) loadGeo()
else setRegion('地区显示未开启', '距离信息未开启')
})

卡片统一用 wowjs 的 animate__zoomIn 入场,样式全部走 var(--card-bg)、var(--theme-color) 这些变量,美化面板换色时两张卡会一起变。

53. 网站信息卡移到列表底部

分类页、标签页文章少的时候,侧栏会被一张「网站信息」卡拉得很长,列表底部反而空一大片。处理办法是:桌面端把 .card-webinfo 从侧栏搬到列表容器末尾,横向铺开;手机端再搬回去。

文件:[Blogroot]/source/js/list-webinfo.js | 改法:新建文件;完整源码可打开本站 /js/list-webinfo.js 对照,整段写入即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* [Blogroot]\source\js\list-webinfo.js */
var MAIN_IDS = ['recent-posts', 'category', 'tag'];
var mq = window.matchMedia('(min-width: 900px)');

function place() {
var webinfo = document.querySelector('.card-webinfo');
if (!webinfo) return;

if (!mq.matches) {
if (webinfo.classList.contains('hg-webinfo-inline')) restore(webinfo);
return;
}

var main = getMain();
if (!main || webinfo.parentElement === main) return;

main.appendChild(webinfo);
webinfo.classList.add('hg-webinfo-inline');
webinfo.classList.remove('wow', 'animate__zoomIn');
webinfo.style.visibility = 'visible';
webinfo.style.animationName = 'none';
}

搬过去之后要挪掉 wow 类和动画,不然卡片会一直停在入场前的透明状态。CSS 用四列网格,随宽度降成三列、两列、一列:

文件:[Blogroot]/source/css/custom.css | 改法:追加到文件末尾。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
.hg-webinfo-inline {
display: block;
width: 100%;
margin: 20px 0 0;
padding: 18px 24px 4px;
border-top: 1px solid var(--border-color, rgba(0, 0, 0, .08));
background: transparent;
}

#recent-posts > .hg-webinfo-inline {
padding: 18px 24px 20px;
border-top: 0;
border-radius: 12px;
background: var(--card-bg);
box-shadow: 0 2px 12px rgba(0, 0, 0, .08);
}

.hg-webinfo-inline > .webinfo {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 8px 28px;
}

移动端 restore() 把卡片放回 #aside-content > .sticky_layout,并去掉 hg-webinfo-inline。最后监听 matchMedia 的 change 和 pjax 的完成事件,来回切页面、缩放窗口都不会丢位置。

54. 画廊:分类大厅与瀑布流

画廊不是外部插件,就是普通页面加几段 HTML 和 CSS。大厅是四张分类卡:

文件:[Blogroot]/source/gallery/index.md | 改法:在正文里新建大厅容器;四个 <figure> 按分类各写一份。

1
2
3
4
5
6
7
8
9
10
11
<div class="hg-gallery-hall">
<figure class="hg-gallery-group">
<img src="/img/gallery/anime/cover.webp" alt="二次元">
<figcaption>
<span class="hg-gallery-group-name">二次元</span>
<p>把喜欢的画面留在这里</p>
<a href="/gallery/anime/"></a>
</figcaption>
</figure>
<!-- 风景 / 萌宠 / 手机 同理 -->
</div>

分类页用 CSS 多列实现瀑布流,不需要 JS 计算高度:

文件:[Blogroot]/source/css/custom.css | 改法:追加到文件末尾,和画廊页面样式放在一起。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
.hg-gallery-grid {
column-count: 3;
column-gap: 12px;
padding: 0 2px;
}

.hg-gallery-grid .hg-gallery-item {
display: block;
break-inside: avoid;
margin: 0 0 12px;
overflow: hidden;
border-radius: 10px;
background: var(--card-bg);
box-shadow: 0 2px 10px rgba(0, 0, 0, .12);
}

.hg-gallery-grid .hg-gallery-item img {
display: block;
width: 100%;
height: auto;
aspect-ratio: 16 / 10;
object-fit: cover;
margin: 0;
border-radius: 0;
transition: transform .45s ease;
}

/* 按位置错开比例,瀑布流才不是一排等高的格子 */
.hg-gallery-grid .hg-gallery-item:nth-child(4n + 2) img { aspect-ratio: 4 / 3; }
.hg-gallery-grid .hg-gallery-item:nth-child(4n + 3) img { aspect-ratio: 3 / 4; }
.hg-gallery-grid .hg-gallery-item:nth-child(4n + 4) img { aspect-ratio: 1 / 1; }

@media screen and (min-width: 1600px) {
.hg-gallery-grid { column-count: 4; }
}
@media screen and (max-width: 991px) {
.hg-gallery-grid { column-count: 2; }
}

手机分类单独加 hg-gallery-grid--mobile,强制竖图比例,避免横图在小屏上只剩一条:

文件:[Blogroot]/source/css/custom.css | 改法:紧接上一段追加,只对带 --mobile 的分类页生效。

1
2
.hg-gallery-grid--mobile .hg-gallery-item:nth-child(4n + 1) img { aspect-ratio: 9 / 16; }
.hg-gallery-grid--mobile .hg-gallery-item:nth-child(4n + 2) img { aspect-ratio: 3 / 4; }

点击原图交给主题自带的 fancybox,缩略图外面套一层带 data-fancybox 的链接即可:

文件:[Blogroot]/source/gallery/<分类>/index.md | 改法:每个缩略图按这个结构写;data-fancybox 同组用同一个名字。

1
2
3
<a class="hg-gallery-item" href="/img/gallery/anime/01.webp" data-fancybox="gallery-anime">
<img src="/img/gallery/anime/01.webp" alt="" loading="lazy">
</a>

两个注意点:

  1. column-count 是纵向填充:每列从上往下排,不是从左到右一行行排。图片顺序会变成「先第一列从上到下,再第二列」,对画廊来说可以接受。
  2. 不用给图片写固定高度,统一用 aspect-ratio。这样图片还没加载时占位比例已经确定,不会因为懒加载回流出瀑布错位。

55. 旧时光:年份分类与跳转

旧时光页的 Markdown 只用主题的 timeline 标签写,脚本一个字都不改正文,只读渲染后的 DOM 做增强:

文件:[Blogroot]/source/time/index.md | 改法:页面正文按原时间轴格式追加;日期写在 <!-- timeline YYYY-MM-DD --> 里。

1
2
3
4
5
6
{% timeline 旧时光,blue %}
<!-- timeline 2026-11-22 -->
1. 第一条记录
2. 第二条记录
<!-- endtimeline -->
{% endtimeline %}

脚本从每个 .timeline-item 的标题里解析 YYYY-MM-DD,拆成「年 + 月日」,再按年份插入分隔节点、年份胶囊和统计:

文件:[Blogroot]/source/js/time-timeline.js | 改法:新建文件;完整源码可打开本站 /js/time-timeline.js 对照,下面拆日期解析。

1
2
3
4
5
6
7
8
9
function parseDate(text) {
var matched = /(\d{4})-(\d{1,2})-(\d{1,2})/.exec(String(text || ''));
if (!matched) return null;
return {
year: matched[1],
md: pad(matched[2]) + '-' + pad(matched[3]),
date: matched[1] + '-' + pad(matched[2]) + '-' + pad(matched[3])
};
}

增强前先设两道保险,避免把别的页面搞坏:

文件:[Blogroot]/source/js/time-timeline.js | 改法:放在 init() 里,位于创建年份节点之前;两道守卫缺一不可。

1
2
3
4
5
6
var timeline = findTimeline(container);
if (!timeline || timeline.getAttribute('data-hg-tl')) return;

// 任意一条日期解析失败,或年份不足 2 个,整块不生效
if (!info) return;
if (years.length < 2) return;

data-hg-tl 是幂等标记,pjax 往返重复执行时直接返回。年份跳转用 scrollTo 而不是直接改 location.hash,因为要减去固定导航的高度:

文件:[Blogroot]/source/js/time-timeline.js | 改法:放在年份胶囊的点击监听里,替换原来的跳转逻辑。

1
2
3
4
5
6
var CHIP_OFFSET = 88;

var top = target.getBoundingClientRect().top +
(window.pageYOffset || document.documentElement.scrollTop || 0) - CHIP_OFFSET;
window.scrollTo({ top: top, behavior: reduce ? 'auto' : 'smooth' });
history.replaceState(null, '', '#' + id);

每个年份分隔器还会统计「多少天 · 多少条记录」,顶部则汇总起止日期、历时天数、更新天数与总条数。统计条目时只数内容区直属的 ol > li,避免把嵌套列表重复算进去:

文件:[Blogroot]/source/js/time-timeline.js | 改法:新增 countEntries() 函数,供年份统计调用。

1
2
3
4
5
6
function countEntries(item) {
var content = item.querySelector('.timeline-item-content');
if (!content) return 0;
var items = content.querySelectorAll(':scope > ol > li, :scope > ul > li');
return items.length || content.querySelectorAll('li').length;
}

样式侧只加 .timeline.hg-tl 前缀,主题原版时间轴完全不受影响;暗色模式单独覆盖背景和分隔线。

56. 公告卡与手机侧边菜单入口

公告卡的内容直接写在 _config.butterfly.yml 的 aside.card_announcement.content 里,用自己的一套 hg-announce 类,不依赖主题卡片原来的排版:

文件:[Blogroot]/_config.butterfly.yml | 改法:找到 aside.card_announcement.content,整段替换成下面的 HTML;缩进保持两格。

1
2
3
4
5
6
7
8
9
10
11
12
card_announcement:
enable: true
content: >-
<div class="hg-announce">
<p class="hg-announce__title"><i class="fas fa-server"></i>网站换到服务器上啦!!</p>
<div class="hg-announce__items">
<a class="hg-announce__item hg-announce__item--domain" href="https://cookiesky.cn">主域名</a>
<a class="hg-announce__item" href="mailto:2451517087@qq.com">联系邮箱</a>
<a class="hg-announce__item hg-announce__item--travel" href="https://travel.moe/go?travel=on" target="_blank" rel="noopener nofollow">异次元之旅</a>
<a class="hg-announce__item hg-announce__item--travellings" href="https://www.travellings.cn/go.html" target="_blank" rel="noopener">开往</a>
</div>
</div>

四条入口用同一套卡片样式,只靠 --domain、--travel、--travellings 修饰符换图标底色:

文件:[Blogroot]/source/css/custom.css | 改法:追加到文件末尾。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
.hg-announce {
display: flex;
flex-direction: column;
gap: 12px;
padding: 2px 0;
}

.hg-announce__item {
display: flex;
align-items: center;
gap: 10px;
padding: 9px 12px;
border: 1px solid color-mix(in srgb, var(--theme-color) 22%, transparent);
border-radius: 10px;
background: color-mix(in srgb, var(--theme-color) 8%, transparent);
color: var(--font-color) !important;
transition: transform .2s ease, background .2s ease;
}

.hg-announce__item:hover {
transform: translateY(-2px);
background: color-mix(in srgb, var(--theme-color) 14%, transparent);
}

手机侧边菜单和桌面导航共用主题的 menu 配置,但这两个外部入口只想出现在手机菜单里。于是用一个小脚本,只往 #sidebar-menus .menus_items 追加节点,桌面 #nav 完全不碰:

文件:[Blogroot]/source/js/mobile-menu-links.js | 改法:新建文件;完整源码可打开本站 /js/mobile-menu-links.js 对照,整段写入。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* [Blogroot]\source\js\mobile-menu-links.js */
const links = [
{ href: 'https://travel.moe/go?travel=on', icon: 'fa-rocket', text: '异次元之旅', rel: 'noopener nofollow' },
{ href: 'https://www.travellings.cn/go.html', icon: 'fa-train', text: '开往', rel: 'noopener' }
];

function inject () {
const menu = document.querySelector('#sidebar-menus .menus_items');
if (!menu || menu.querySelector('.hg-sidebar-extra')) return;

links.forEach(item => {
const wrap = document.createElement('div');
wrap.className = 'menus_item hg-sidebar-extra';

const a = document.createElement('a');
a.className = 'site-page';
a.href = item.href;
a.target = '_blank';
a.rel = item.rel;

const icon = document.createElement('i');
icon.className = 'fas ' + item.icon + ' fa-fw';

const text = document.createElement('span');
text.textContent = ' ' + item.text;

a.append(icon, text);
wrap.append(a);
menu.append(wrap);
});
}

.hg-sidebar-extra 既是样式钩子,也是防止 pjax 重复注入的标记。脚本要在 DOMContentLoaded 和 pjax:complete 各跑一次。

57. Cookie 同意与第三方服务门控

统计和评论都是第三方服务,默认不该在用户做选择前加载。本站的做法分两层:

第一层,构建期剥离统计脚本。 主题会把 busuanzi 的 <script> 写死在页面里,用 after_render:html 过滤器统一删掉:

文件:[Blogroot]/scripts/consent-gate.js | 改法:新建文件,整段写入。

1
2
3
4
/* [Blogroot]\scripts\consent-gate.js */
hexo.extend.filter.register('after_render:html', function (html) {
return html.replace(/<script\b[^>]*\bbusuanzi\b[^>]*>\s*<\/script>/gi, '');
});

第二层,运行期按选择加载。 选择存在 localStorage 的 hgConsent 里,只有 v: 1 才认:

文件:[Blogroot]/source/js/consent.js | 改法:新建文件;完整源码可打开本站 /js/consent.js 对照,下面拆读取与门控逻辑。

1
2
3
4
5
6
7
8
9
10
11
var KEY = 'hgConsent';

function read () {
try {
var raw = w.localStorage.getItem(KEY);
if (!raw) return null;
var v = JSON.parse(raw);
if (!v || v.v !== 1) return null;
return { analytics: v.analytics === true, comments: v.comments === true };
} catch (e) { return null; }
}

统计同意后才动态插入脚本:

文件:[Blogroot]/source/js/consent.js | 改法:替换 loadBusuanzi() 函数;统计脚本地址按你用的版本改。

1
2
3
4
5
6
7
8
function loadBusuanzi () {
if (w.__hgBszLoaded) return;
w.__hgBszLoaded = true;
var s = d.createElement('script');
s.async = true;
s.src = 'https://cdn.busuanzi.cc/busuanzi/3.6.9/busuanzi.min.js';
(d.body || d.head).appendChild(s);
}

评论拒绝时直接把评论区 DOM 移除;之后改成允许,需要刷新一次页面才能重新初始化 Twikoo:

文件:[Blogroot]/source/js/consent.js | 改法:替换 stripComments() 函数;评论容器 ID 以你的主题为准。

1
2
3
4
5
6
7
function stripComments () {
var ids = ['post-comment', 'to_comment', 'newest-comments'];
for (var i = 0; i < ids.length; i++) {
var node = d.getElementById(ids[i]);
if (node && node.parentNode) node.parentNode.removeChild(node);
}
}

三个选择:全部接受、接受部分(统计 / 评论分别勾选)、不接受。关闭弹窗或按 Esc 视为同意全部,这一点要在弹窗文案里写清楚。选择变化时派发自定义事件,侧栏地区卡片等模块监听后立即响应:

文件:[Blogroot]/source/js/consent.js | 改法:放在 decide() 里,保存选择并关闭弹窗之后派发。

1
d.dispatchEvent(new w.CustomEvent('hg-consent-change', { detail: state }));

弹窗样式全部走 var(--card-bg)、var(--theme-color)、var(--on-theme),暗色模式和美化面板换色都能自动适配。入口要留一个:美化设置 → 布局与部件 → Cookie 与隐私,调用 window.hgOpenConsent() 重新打开。

58. Service Worker 静态资源缓存

HTML 必须网络优先,否则文章更新后用户看到的还是旧页面;带版本号的 CSS / JS / 图片可以缓存优先,后台再更新。两个缓存分开存:

文件:[Blogroot]/source/sw.js | 改法:新建文件;完整源码可打开本站 /sw.js 对照,先写缓存名和匹配规则。

1
2
3
4
5
6
/* [Blogroot]\source\sw.js 节选 */
const VERSION = '20261122a'
const STATIC_CACHE = 'hg-static-' + VERSION
const PAGE_CACHE = 'hg-page-' + VERSION
const STATIC_PATH = /^\/(?:css|js|fonts?|img|lib)\//
const ASSET_EXT = /\.(?:css|js|mjs|woff2?|ttf|otf|webp|avif|png|jpe?g|gif|svg|ico)$/i

页面请求:

文件:[Blogroot]/source/sw.js | 改法:放在 fetch 事件里,先处理页面导航请求。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if (request.mode === 'navigate') {
event.respondWith(
fetch(request).then(function (response) {
if (response && response.ok) {
const copy = response.clone()
caches.open(PAGE_CACHE).then(function (cache) { cache.put(request, copy) })
}
return response
}).catch(function () {
return caches.match(request).then(function (hit) {
return hit || caches.match('/')
})
})
)
return
}

静态资源:

文件:[Blogroot]/source/sw.js | 改法:紧接页面分支之后,处理同源静态资源。

1
2
3
4
5
6
7
8
9
10
11
event.respondWith(
caches.open(STATIC_CACHE).then(function (cache) {
return cache.match(request).then(function (hit) {
const network = fetch(request).then(function (response) {
if (response && response.ok) cache.put(request, response.clone())
return response
}).catch(function () { return hit })
return hit || network
})
})
)

几个关键约束:

  • 跨域请求直接放行,不接管统计、评论、地区接口。
  • request.method !== 'GET' 和带 Range 的请求(音视频拖动)不缓存。
  • install 里 skipWaiting(),activate 里清掉旧版本缓存并 clients.claim()。
  • 每次改 CSS / JS,记得同时改 custom.css?v=... 和 sw.js 的 VERSION。只改文件不改版本号,缓存优先会继续吐旧文件,这是最容易出现的「我明明改了怎么没生效」。

注册放在页面加载完成之后,不抢首屏带宽:

文件:[Blogroot]/source/js/sw-register.js | 改法:新建文件,整段写入;再把它加进 inject.bottom。

1
2
3
4
/* [Blogroot]\source\js\sw-register.js */
w.addEventListener('load', function () {
navigator.serviceWorker.register('/sw.js', { updateViaCache: 'none' }).catch(function () {})
})

调试时用 DevTools → Application → Service Workers 勾选 Update on reload,或者直接 Unregister 再刷新。

59. 图片、字体与前端资源的瘦身

首页封面是最大的一块。原图 bg1.png 约 6.6MB,转成 bg1.webp 后只有 97KB;另一张背景 bg.png 从 3.55MB 降到 136KB,移动端单独出 bg-mobile.webp。转换命令(安装 cwebp 后):

执行位置:博客根目录终端 | 作用:把原图转成 WebP,输出文件放在同目录。

1
cwebp -q 82 bg1.png -o bg1.webp

字体是第二块。霞鹜文楷全量字体太大,按站内实际用字加 GB2312 常用字做子集,重建后的子集覆盖 7,820 个字形,繁体与生僻字不再回退系统字体。生成后放 [Blogroot]/source/font/,并在 @font-face 里指过去:

文件:[Blogroot]/source/css/custom.css | 改法:追加字体声明;字体文件先放进 source/font/。

1
2
3
4
5
@font-face {
font-family: 'myfont';
src: url('/font/霞鹜文楷.full.woff2') format('woff2');
font-display: swap;
}

子集文件虽然还是 MB 级,但比全量小得多,配合首屏预加载,正文不会出现明显的字体闪烁:

文件:[Blogroot]/_config.butterfly.yml | 改法:加到 inject.head 的列表里,和其它 <link> 并列。

1
- <link rel="preload" as="font" type="font/woff2" href="/font/%E9%9C%9E%E9%B9%9C%E6%96%87%E6%A5%B7.full.woff2" crossorigin>

其它几项:

  1. wowjs 的 CSS 和 JS 全部放本地,去掉第三方 CDN 请求,离线也能正常入场。
  2. 主题 index.css 开启 Stylus 压缩:stylus.compress: true。
  3. 过大的第三方弹窗(比如节日弹窗用的 sweetalert2)改成按需加载,没触发节日就不下载。
  4. 头像、友链截图、画廊缩略图统一转 WebP,并加 loading="lazy"。
  5. 检查首屏:DevTools → Network 按体积排序,超过 200KB 的图片和字体优先处理。

体积优化不要一次改十几项,改一项、清一次缓存、对比一次加载瀑布图,才知道是哪一项真正有效。

60. 订阅源 BOM 与 custom.css 截断修复

订阅源中文乱码。 Edge 和部分阅读器在响应头没有 charset 时,会把 atom.xml 当 GBK 解码,XML 声明里的 encoding="utf-8" 兜不住。解决办法是构建完成后给订阅源补 UTF-8 BOM:

文件:[Blogroot]/scripts/feed-bom.js | 改法:新建文件,整段写入。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* [Blogroot]\scripts\feed-bom.js */
'use strict';

hexo.extend.filter.register('after_generate', function () {
const feed = hexo.config.feed;
if (!feed || !feed.path) return;

const route = hexo.route;
const feedPath = route.format(feed.path);
const data = route.get(feedPath);

if (typeof data === 'string' && data.charCodeAt(0) !== 0xfeff) {
route.set(feedPath, '\uFEFF' + data);
} else if (Buffer.isBuffer(data) && !(data[0] === 0xef && data[1] === 0xbb && data[2] === 0xbf)) {
route.set(feedPath, Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), data]));
}
});

字符串和 Buffer 两种返回类型都要处理,且要判断 BOM 是否已经存在,避免重复添加。

custom.css 截断。 这次遇到一个很隐蔽的问题:文件里有一段 @-webkit-keyframes 没有闭合,浏览器解析到那里之后,把后面所有规则整段丢弃。表现是「前面几节样式正常,后面突然全失效」,很容易误判成选择器写错。修复前后的生效规则数是 202 → 601。

排查和预防:

  1. 用 DevTools → Sources 打开 custom.css,看最后一条被识别的规则停在哪一行,问题通常就在它附近。
  2. 大段注释里不要嵌套 /* */,一个多余的 */ 就会让解析器提前结束注释。
  3. 改完 CSS 用 npx stylelint 或任意 CSS 校验器过一遍括号配对。
  4. 给 custom.css 的引用加版本参数,改一次升一次;配合 Service Worker 时,sw.js 的 VERSION 也要一起升。

改完怎么验证与部署

十节都改完后,不要直接上传,先在本地走一遍:

  1. 生成:在博客根目录执行 ./node_modules/.bin/hexo generate(Windows 下也可用 hexo generate)。看最后一行是不是 Generated,有报错先解决再继续。
  2. 本地预览:执行 hexo server,打开 http://localhost:4000,重点检查首页多栏、侧栏两张卡、画廊、旧时光、公告卡和手机菜单。
  3. 硬刷新:改过 CSS / JS 后按 Ctrl + F5。如果启用了 Service Worker,再到 DevTools → Application → Service Workers 点一次 Update,否则看到的可能还是缓存里的旧文件。
  4. 检查控制台:F12 看 Console 有没有 404 或 Uncaught,Network 里确认 custom.css、本节新增的 JS 文件、sw.js 的版本参数已经更新。
  5. 部署:把生成的 public/ 目录按你原来的方式上传(Nginx 静态托管、GitHub Pages、Vercel 或 hexo deploy 都行)。上传后关掉浏览器缓存再访问一次,确认线上和本地一致。

上线前再核对三件事:

  • _config.yml 和 _config.butterfly.yml 的缩进没有错位,YAML 对空格数量很敏感。
  • 新增的 scripts/*.js 在博客根目录的 scripts 文件夹里,不是在主题目录里;这样升级主题不会丢。
  • 改过 custom.css 或任何 JS 后,_config.butterfly.yml 里的 ?v= 版本号和 sw.js 的 VERSION 是否一起改了。

这篇把第 51 ~ 60 个魔改写完了。首页多栏、侧栏卡片、画廊、旧时光、公告入口、Cookie、缓存与资源瘦身都已经落地。第 61 个魔改已经接着写:hexo魔改教程(六):侧栏内容卡全宽展开。