直接內嵌百度分享官方代碼時,頁面載入會阻塞於 shell_v2.js 的下載與執行,導致:
src 的 <script> 佔位標籤。src**:在 window.onload(所有關鍵資源載入完)後,動態設定最後一支腳本的 src 觸發下載。<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>延遲載入百度分享 Demo</title>
<style>
body { font-family: sans-serif; padding: 2rem; line-height: 1.6; }
#baidu-share { margin: 2rem 0; padding: 1rem; border: 1px dashed #ccc; }
.share-btn { display: inline-block; width: 32px; height: 32px; margin: 0 4px; background: #eee; text-align: center; line-height: 32px; border-radius: 4px; color: #333; text-decoration: none; }
.share-btn:hover { background: #ddd; }
</style>
</head>
<body>
<h1>文章標題</h1>
<p>這是主要內容區塊,優先渲染,不受分享按鈕影響。</p>
<!-- 分享按鈕容器:純 HTML,無外部腳本 -->
<div id="baidu-share">
<div id="bdshare" class="bdshare_t bds_tools_32 get-codes-bdshare">
<a class="bds_tsina share-btn" title="分享到新浪微博">微博</a>
<a class="bds_qzone share-btn" title="分享到 QQ 空間">Qzone</a>
<a class="bds_tqq share-btn" title="分享到騰訊微博">騰訊微博</a>
<a class="bds_weixin share-btn" title="分享到微信">微信</a>
<span class="bds_more share-btn">更多</span>
</div>
<!-- 兩支無 src 的佔位腳本 -->
<script id="bdshare_js" type="text/javascript" data="type=tools&uid=0"></script>
<script id="bdshell_js" type="text/javascript"></script>
</div>
<footer>頁尾資訊...</footer>
<script>
// 延遲載入:window.onload 確保主內容已可互動
window.addEventListener('load', loadBaiduShare);
function loadBaiduShare() {
const shell = document.getElementById('bdshell_js');
if (!shell) return;
// 百度官方:帶時間戳防快取
shell.src = 'https://bdimg.share.baidu.com/static/js/shell_v2.js?cdnversion=' + Math.ceil(Date.now() / 3600000);
// 可選:載入失敗靜默處理,不拋錯到主控台
shell.onerror = () => console.warn('[Baidu Share] 載入失敗,已忽略');
}
</script>
</body>
</html>
| 項目 | 官方原始碼 | 延遲載入版 |
|---|---|---|
| HTML 結構 | 同步內嵌 | 同步渲染,腳本延遲 |
shell_v2.js 載入時機 | 解析到 <script src> 時立即下載 | window.onload 後動態注入 src |
| 阻塞主線程 | 是 | 否 |
| 第三方故障影響 | 可能導致頁面卡死 | 完全隔離 |
| LCP / FCP 影響 | 負面 | 零影響 |
/**
* 延遲載入第三方腳本
* @param {string} scriptId - script 標籤 id
* @param {string} src - 腳本 URL(可含動態參數)
* @param {number} [delay=0] - onload 後額外延遲 ms
*/
function lazyLoadScript(scriptId, src, delay = 0) {
const el = document.getElementById(scriptId);
if (!el) return;
setTimeout(() => {
el.src = src;
el.onerror = () => console.warn(`[LazyLoad] ${scriptId} failed`);
}, delay);
}
// 使用
window.addEventListener('load', () => {
lazyLoadScript('bdshell_js', 'https://bdimg.share.baidu.com/static/js/shell_v2.js?cdnversion=' + Math.ceil(Date.now()/3600000));
// 同理可延遲:GA、廣告、客服聊天插件、地圖 SDK...
});
使用 Chrome DevTools → Performance 或 Lighthouse 對比:
shell_v2.js 從「早期阻塞請求」移至「閒時載入」。核心原則: 任何非首屏關鍵、非同源、不可控的第三方腳本,都應採用「HTML 先行、JS 延遲」模式載入。這是前端效能優化的黃金法則之一。