❝前段时间面试字节,面试官对我的埋点项目比较感兴趣,聊着聊着突然来了一个问题(原话):既然说到了这样一个叫做监控,其实有一个比较经典的 case 也想探讨一下,就是比如说你有在开发过程中,假如你的页面被反馈说白屏了,对吧?正常情况下你要去排查问题、解决问题,那我想让你就是简单的描述一下你会去怎么去做,就是把你要准备处理的过程也描述一下。
我的回答:有提到检查 DOM 挂载
/ 网络请求状态
/ JS 执行错误
,但未覆盖资源加载失败
、CDN 异常
等场景。虽然有简单了解过页面白屏相关的内容,不过还没在实习工作中遇到过这类问题,还是缺少了些系统性排查的思维,这篇文章就来总结学习一下。(先了解页面白屏原因 -> 梳理一下排查思路 -> 学习下如何在SDK中实现白屏检测)
❝白屏问题本质上是浏览器渲染流水线的断裂,从 DNS 解析 -> 资源加载 -> JS 执行 -> DOM 构建 -> 渲染树生成 -> 页面绘制的完整链路中,任一环节的异常都可能导致最终呈现的空白。
图为原创, 若需转载 可以备注出处✨
❝看完这么复杂的排查流程, 来思考下一个页面白屏 真的值得如此认真对待吗? (问问那些大厂c端的大佬们就知道了)
用户体量越大, 页面白屏时间能带来的负面影响就越能呈现指数级增长, 比如说:
- 业务层面
:电商场景下每增加1秒白屏时间转化率下降7% - 技术层面
:可能引发雪崩效应(如 CDN 故障导致全站不可用) - 体验层面
:用户留存率下降40%+
// Step 1 - 检测文档加载阶段
console.log('DOMContentLoaded:', performance.timing.domContentLoadedEventEnd - performance.timing.navigationStart);
console.log('Load Event:', performance.timing.loadEventEnd - performance.timing.navigationStart);
// Step 2 - 检查关键错误
window.addEventListener('error', e => {
console.error('Global Error:', e.message, e.filename, e.lineno);
}, true);
// Step 3 - 验证 DOM 挂载点(React/Vue 重点)
const rootNode = document.getElementById('root');
if (!rootNode || rootNode.childNodes.length === 0) {
console.error('挂载节点异常:', rootNode);
}
// Step 4 - 网络状态检测
fetch('/health-check').catch(e => {
console.error('网络连通性异常:', e);
});
典型问题场景:
使用 Chrome DevTools 的 Network 面板:
过滤 JS|CSS|IMG
类型资源
检查关键资源的:
右键资源 → Copy as cURL
验证 CDN 可用性
# 多节点探测(需安装 httpie)
http https://cdn.example.com/main.js --verify=no \
--headers \
--proxy=http:http://1.1.1.1:8080 \ # 切换不同代理节点
--download > /dev/null
# DNS 污染检测
nslookup cdn.example.com 8.8.8.8 # 对比不同 DNS 结果
nslookup cdn.example.com 114.114.114.114
经典案例:
某站点因 CDN 节点未同步最新证书,导致部分用户浏览器拦截 HTTPS 请求引发白屏
<!-- 带 SRI 校验的资源加载 -->
<scriptsrc="https://cdn.example.com/react.production.min.js"
integrity="sha384-xxxx"
crossorigin="anonymous"></script>
排查要点:
Integrity checksum failed
错误
openssl dgst -sha384 -binary react.production.min.js | openssl base64 -A
Vue 场景:
newVue({
render: h =>h(App)
}).$mount('#app') // 若 #app 节点不存在,静默失败!
解决方案:
const root = document.getElementById('app');
if (!root) {
document.write('容器丢失,降级显示基础内容');
} else {
newVue({ render: h =>h(App) }).$mount(root);
}
React 场景:
// 错误边界组件(捕获渲染层错误)
classErrorBoundaryextendsReact.Component {
componentDidCatch(error) {
Sentry.captureException(error);
window.location.reload(); // 降级策略
}
render() { returnthis.props.children; }
}
// 使用方式
<ErrorBoundary>
<App />
</ErrorBoundary>
检测方法:
about:blank
清空页面z-index
异常导致元素不可见典型案例:
某页面因 body { display: none !important; }
内联样式导致白屏
Long Tasks API:
const observer = newPerformanceObserver(list => {
list.getEntries().forEach(entry => {
if (entry.duration > 50) {
console.warn('主线程阻塞:', entry);
}
});
});
observer.observe({ entryTypes: ['longtask'] });
Chrome Memory 面板操作:
Detached DOM tree
检查未释放节点典型案例:
未销毁的 WebSocket 监听器持续累积导致内存溢出
// 使用 Feature Detection 代替 UA 检测
if (!('IntersectionObserver'inwindow)) {
loadPolyfill('intersection-observer').then(initApp);
}
// 检查页面是否被注入第三方脚本
const thirdPartyScripts = Array.from(document.scripts).filter(
s => !s.src.includes(window.location.hostname)
);
if (thirdPartyScripts.length > 0) {
reportException('运营商劫持', thirdPartyScripts);
}
Service Worker
缓存:
navigator.serviceWorker.getRegistrations().then(regs => {
regs.forEach(reg => reg.unregister())
})
❝这里就给大家放部分最近写的代码, 主要用的是
动态检测根节点
+黄金比例采样算法
+采样点检测
三种方法来检测白屏情况, 感兴趣的也可以去我的代码仓库看下完整的代码 - ByteTop - 轻量级Web端埋点监控平台
const rootSelectors = ["#root", "#app", "#main", "#container"];
const rootNode = rootSelectors.find(selector =>
document.querySelector(selector)
) || "body";
const wrapperSet = newSet(["html", "body", rootNode.toLowerCase()]);
const goldenRatio = 0.618;
const points = Array.from({ length: config.sampleCount }, (_, i) => ({
x: i % 2 === 0
? window.innerWidth * goldenRatio * Math.random()
: window.innerWidth - window.innerWidth * goldenRatio * Math.random(),
y: window.innerHeight * goldenRatio * Math.random()
}));
const identifiers = [
element.tagName.toLowerCase(), // 标签特征
element.id ? `#${element.id}` : "", // ID 特征
...Array.from(element.classList).map(c =>`.${c}`) // 类名特征
];
if (identifiers.some(id => wrapperSet.has(id))) {
emptyCount++;
}
return emptyCount / config.sampleCount >= config.threshold;
interfaceCheckWhiteScreenOptions {
/** 采样点数量 (默认: 20) */
sampleCount?: number;
/** 空白点判定阈值 (0-1, 默认 0.8) */
threshold?: number;
/** 排除的骨架屏类名 (默认: 'skeleton') */
skeletonClass?: string;
}
const checkWhiteScreen = (options?: CheckWhiteScreenOptions): boolean => {
const config = {
sampleCount: 20,
threshold: 0.8,
skeletonClass: "skeleton",
...options,
};
try {
// 1. 排除骨架屏场景
if (document.getElementsByClassName(config.skeletonClass).length > 0) {
returnfalse;
}
// 2. 动态检测根节点
const rootSelectors = ["#root", "#app", "#main", "#container"];
const rootNode =
rootSelectors.find((selector) =>document.querySelector(selector)) ||
"body";
const wrapperSet = newSet(["html", "body", rootNode.toLowerCase()]);
// 3. 黄金比例采样算法
const goldenRatio = 0.618;
const points = Array.from({ length: config.sampleCount }, (_, i) => ({
x:
i % 2 === 0
? window.innerWidth * goldenRatio * Math.random()
: window.innerWidth - window.innerWidth * goldenRatio * Math.random(),
y: window.innerHeight * goldenRatio * Math.random(),
}));
// 4. 采样点检测
let emptyCount = 0;
points.forEach((point) => {
const element = document.elementFromPoint(point.x, point.y);
if (!element) {
emptyCount++;
return;
}
const identifiers = [
element.tagName.toLowerCase(),
element.id ? `#${element.id}` : "",
...Array.from(element.classList).map((c) =>`.${c}`),
];
if (identifiers.some((id) => wrapperSet.has(id))) {
emptyCount++;
}
});
console.log("emptyCount", emptyCount, " config:", config);
// 5. 阈值判断
return emptyCount / config.sampleCount >= config.threshold;
} catch (e) {
console.error("[白屏检测异常]", e);
returnfalse;
}
};
exportdefault checkWhiteScreen;
// // 自定义配置
// const isWhite = checkWhiteScreen({
// sampleCount: 30,
// threshold: 0.75,
// skeletonClass: 'loading-skeleton'
// });
// // 移动端适配配置
// checkWhiteScreen({
// sampleCount: 15, // 减少采样点
// threshold: 0.7 // 降低阈值
// });
// // 后台管理系统
// checkWhiteScreen({
// skeletonClass: 'ant-skeleton' // 匹配UI框架
// });
// // 高精度检测
// checkWhiteScreen({
// sampleCount: 50, // 增加采样密度
// threshold: 0.9 // 严格判定
// });
还没有使用过我们刷题网站(https://fe.ecool.fun/)或者刷题小程序的同学,如果近期准备或者正在找工作,千万不要错过,题库已经录入 1600 多道前端面试题,除了八股文,还有现在面试官青睐的场景题,甚至最热的AI与前端相关的面试题已经更新,努力做全网最全最新的前端刷题网站。
有会员购买、辅导咨询的小伙伴,可以通过下面的二维码,联系我们的小助手。