JavaScript!十個(gè)強(qiáng)到離譜的API,90%的人都不知道
環(huán)境:SpringBoot3.4.2
1. 簡(jiǎn)介
在Web開發(fā)中,JavaScript 已成為構(gòu)建動(dòng)態(tài)、交互式應(yīng)用的核心工具。隨著瀏覽器能力不斷擴(kuò)展,開發(fā)者已不再局限于基礎(chǔ)DOM操作,而是能通過豐富的原生API實(shí)現(xiàn)復(fù)雜功能。從實(shí)時(shí)通信的Web Sockets到離線存儲(chǔ)的IndexedDB等等,這些API覆蓋了網(wǎng)絡(luò)請(qǐng)求、性能優(yōu)化等關(guān)鍵場(chǎng)景。
本篇文章精選了10個(gè)神級(jí)API,涵蓋頁(yè)面生命周期管理、跨標(biāo)簽通信、數(shù)據(jù)可視化優(yōu)化等前沿需求,將幫助開發(fā)者突破傳統(tǒng)開發(fā)邊界,以更簡(jiǎn)潔的代碼實(shí)現(xiàn)更強(qiáng)大的功能。
2.實(shí)戰(zhàn)案例
2.1 頁(yè)面可見性
當(dāng)用戶切換標(biāo)簽頁(yè)時(shí),自動(dòng)暫停視頻播放或停止后臺(tái)輪詢?nèi)蝿?wù),以節(jié)省資源。
HTML頁(yè)面
<div class="api-section">
<h2>1. Page Visibility API</h2>
<p>當(dāng)頁(yè)面隱藏時(shí)自動(dòng)暫停視頻播放</p>
<div class="video-container">
<video id="myVideo" controls>
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
您的瀏覽器不支持HTML5視頻
</video>
</div>
<div class="info">狀態(tài): <span id="visibilityStatus">頁(yè)面可見</span></div>
</div>JavaScript實(shí)現(xiàn)
const video = document.querySelector('#myVideo')
const visibilityStatus = document.querySelector('#visibilityStatus')
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
video.pause();
visibilityStatus.textContent = '頁(yè)面隱藏 - 視頻已暫停'
} else {
video.play();
visibilityStatus.textContent = '頁(yè)面可見 - 視頻已播放'
}
});最終效果
圖片
當(dāng)我們將頁(yè)面最小化后或者切換標(biāo)簽頁(yè)時(shí),這里的播放會(huì)自動(dòng)暫停,切換回來時(shí)會(huì)自動(dòng)的播放。
2.2 Web共享API
調(diào)用系統(tǒng)原生分享對(duì)話框,允許用戶一鍵分享當(dāng)前頁(yè)面內(nèi)容至社交平臺(tái)或郵件,無(wú)需依賴第三方庫(kù),簡(jiǎn)化移動(dòng)端分享流程。
HTML頁(yè)面
<div class="api-section">
<h2>2. Web Share API</h2>
<p>調(diào)用系統(tǒng)原生分享對(duì)話框</p>
<button id="shareBtn" class="btn">分享本頁(yè)面</button>
<div id="shareOutput" class="output"></div>
</div>JavaScript實(shí)現(xiàn)
document.getElementById('shareBtn').addEventListener('click', async () => {
const output = document.querySelector('#shareOutput');
if (navigator.share) {
try {
await navigator.share({
title: '現(xiàn)代瀏覽器API演示',
text: '查看這些強(qiáng)大的瀏覽器API示例',
url: window.location.href,
});
output.textContent = '分享成功!';
} catch (err) {
output.textContent = '分享取消或出錯(cuò): ' + err.message;
}
} else {
output.textContent = '您的瀏覽器不支持Web Share API';
}
});最終效果
圖片
圖片
2.3 跨標(biāo)簽頁(yè)通信
實(shí)現(xiàn)跨標(biāo)簽頁(yè)實(shí)時(shí)通信,通過統(tǒng)一頻道發(fā)送和接收消息,適用于多標(biāo)簽頁(yè)協(xié)同操作(如購(gòu)物車同步),無(wú)需輪詢或復(fù)雜后端支持。
HTML頁(yè)面
<!-- 發(fā)送消息頁(yè)面index.html -->
<div class="api-section">
<h2>3. Broadcast Channel API</h2>
<p>跨標(biāo)簽頁(yè)通信 (打開多個(gè)標(biāo)簽頁(yè)測(cè)試)</p>
<button id="sendBroadcastBtn" class="btn">發(fā)送廣播消息</button>
<div id="broadcastOutput" class="output">等待接收消息...</div>
</div>
<!--接收消息頁(yè)面-->
<div class="message"></div>JavaScript實(shí)現(xiàn)
// 發(fā)送消息頁(yè)面index.html
const broadcastChannel = new BroadcastChannel('demo_channel');
const broadcastOutput = document.querySelector('#broadcastOutput');
document.querySelector('#sendBroadcastBtn').addEventListener('click', () => {
const message = `選擇了《Spring Boot 3實(shí)戰(zhàn)案例200講》電子書`;
broadcastChannel.postMessage(message);
broadcastOutput.textContent = `已發(fā)送: ${message}`;
});
// 接收消息頁(yè)面message.html
const broadcastChannel = new BroadcastChannel('demo_channel');
const message = document.querySelector('.message');
broadcastChannel.onmessage = (e) => {
message.textContent = `已接收: ${e.data}`;
};最終效果
圖片
圖片
2.4 數(shù)字格式化
國(guó)際化數(shù)字格式化工具,支持貨幣、百分比等格式本地化顯示(如千位分隔符、貨幣符號(hào)),確保數(shù)字在不同語(yǔ)言環(huán)境下正確呈現(xiàn)。
HTML頁(yè)面
<div class="api-section">
<h2>4. Intl.NumberFormat</h2>
<p>數(shù)字和貨幣格式化</p>
<button id="formatNumberBtn" class="btn">格式化數(shù)字</button>
<button id="formatCurrencyBtn" class="btn">格式化貨幣</button>
<div id="numberFormatOutput" class="output"></div>
</div>JavaScript實(shí)現(xiàn)
document.querySelector('#formatNumberBtn').addEventListener('click', () => {
const number = 1234567.89
const formatted = new Intl.NumberFormat('en-US').format(number)
document.querySelector('#numberFormatOutput').textContent = `格式化結(jié)果: ${formatted}`
});
document.querySelector('#formatCurrencyBtn').addEventListener('click', () => {
const number = 1234567.89;
const formatted = new Intl.NumberFormat('zh-CN', {
style: 'currency',
currency: 'CNY'
}).format(number)
document.querySelector('#numberFormatOutput').textContent = `貨幣格式化結(jié)果: ${formatted}`
});最終效果


2.5 監(jiān)聽元素與可視窗口
高效監(jiān)聽元素與視口的交叉狀態(tài),實(shí)現(xiàn)圖片懶加載或廣告曝光統(tǒng)計(jì),替代傳統(tǒng)滾動(dòng)事件監(jiān)聽,減少性能損耗并優(yōu)化頁(yè)面加載速度。
HTML頁(yè)面
<div class="api-section">
<h2>5. IntersectionObserver</h2>
<p>圖片懶加載 (向下滾動(dòng)查看效果)</p>
<div style="height: 100px;"></div>
<img data-src="https://picsum.photos/600/400?random=1" alt="Lazy Image 1">
<img data-src="https://picsum.photos/600/400?random=2" alt="Lazy Image 2">
<img data-src="https://picsum.photos/600/400?random=3" alt="Lazy Image 3">
<div style="height: 100px;"></div>
<div id="lazyLoadOutput" class="output">等待圖片進(jìn)入視口...</div>
</div>JavaScript實(shí)現(xiàn)
const lazyLoadObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target
img.src = img.dataset.src
lazyLoadObserver.unobserve(img)
document.querySelector('#lazyLoadOutput').textContent += `\n已加載圖片: ${img.alt}`
}
})
})
document.querySelectorAll('img[data-src]').forEach(img => {
lazyLoadObserver.observe(img)
})最終效果
圖片
2.6 觀察元素大小變化
HTML實(shí)現(xiàn)
<div class="api-section">
<h2>6. ResizeObserver</h2>
<p>監(jiān)聽元素尺寸變化 (拖動(dòng)右下角調(diào)整大小)</p>
<div id="box">調(diào)整我的大小</div>
<div id="resizeOutput" class="output">尺寸: 等待調(diào)整...</div>
</div>JavaScript實(shí)現(xiàn)
const resizeObserver = new ResizeObserver(entries => {
for (const entry of entries) {
const { width, height } = entry.contentRect
document.querySelector('#resizeOutput').textContent =
`尺寸: ${width.toFixed(0)}px × ${height.toFixed(0)}px`
}
})
resizeObserver.observe(document.querySelector('#box'))最終效果
圖片
2.7 異步剪貼板操作
異步讀寫剪貼板內(nèi)容,支持無(wú)權(quán)限提示的文本復(fù)制(如優(yōu)惠券代碼),替代傳統(tǒng)document.execCommand,提供更安全可靠的剪貼板操作。
HTML頁(yè)面
<div class="api-section">
<h2>7. Clipboard API</h2>
<p>復(fù)制文本到剪貼板</p>
<div class="coupon-container">
<input type="text" id="coupon" value="COUPON2025" readonly>
<button id="copyBtn" class="btn">復(fù)制</button>
</div>
<div id="clipboardOutput" class="output"></div>
</div>JavaScript實(shí)現(xiàn)
document.getElementById('copyBtn').addEventListener('click', async () => {
const output = document.querySelector('#clipboardOutput')
try {
await navigator.clipboard.writeText(document.getElementById('coupon').value)
output.textContent = '已復(fù)制到剪貼板!'
} catch (err) {
output.textContent = '復(fù)制失敗: ' + err.message
}
})最終效果
圖片
2.8 URL查詢字符串解析
簡(jiǎn)化URL查詢參數(shù)解析與構(gòu)建,支持動(dòng)態(tài)增刪改查參數(shù)(如分頁(yè)、篩選條件),無(wú)需手動(dòng)拼接字符串,提升前端路由和API調(diào)用效率。
HTML頁(yè)面
<div class="api-section">
<h2>8. URLSearchParams</h2>
<p>解析和構(gòu)建URL查詢字符串</p>
<button id="parseUrlBtn" class="btn">解析當(dāng)前URL參數(shù)</button>
<button id="buildUrlBtn" class="btn">構(gòu)建新URL</button>
<div id="urlOutput" class="output"></div>
</div>JavaScript實(shí)現(xiàn)
document.querySelector('#parseUrlBtn').addEventListener('click', () => {
const params = new URLSearchParams(window.location.search)
const output = document.querySelector('#urlOutput')
if (params.toString() === '') {
output.textContent = '當(dāng)前URL沒有查詢參數(shù)'
} else {
let result = '解析結(jié)果:\n'
params.forEach((value, key) => {
result += `${key}: ${value}\n`
});
output.textContent = result
}
});
document.querySelector('#buildUrlBtn').addEventListener('click', () => {
const params = new URLSearchParams()
params.append('page', '2')
params.append('sort', 'desc')
params.append('q', '瀏覽器API')
const url = `${window.location.origin}${window.location.pathname}?${params.toString()}`
document.querySelector('#urlOutput').textContent = `構(gòu)建的URL: ${url}`
});最終效果

2.9 終止異步操作
中止異步操作(如fetch請(qǐng)求),通過信號(hào)對(duì)象統(tǒng)一管理取消邏輯,避免資源浪費(fèi),適用于搜索建議、實(shí)時(shí)數(shù)據(jù)流等可中斷場(chǎng)景。
HTML頁(yè)面
<div class="api-section">
<h2>9. AbortController</h2>
<p>中止fetch請(qǐng)求</p>
<button id="fetchBtn" class="btn">發(fā)起請(qǐng)求</button>
<button id="abortBtn" class="btn btn-secondary">中止請(qǐng)求</button>
<div id="fetchOutput" class="output"></div>
</div>JavaScript實(shí)現(xiàn)
let fetchController;
document.querySelector('#fetchBtn').addEventListener('click', async () => {
const output = document.querySelector('#fetchOutput')
fetchController = new AbortController()
try {
output.textContent = '請(qǐng)求中...'
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
signal: fetchController.signal
})
const data = await response.json()
output.textContent = `請(qǐng)求成功: ${JSON.stringify(data).substring(0, 100)}...`
} catch (err) {
if (err.name === 'AbortError') {
output.textContent = '請(qǐng)求已被中止'
} else {
output.textContent = '請(qǐng)求出錯(cuò): ' + err.message
}
}
});
document.querySelector('#abortBtn').addEventListener('click', () => {
if (fetchController) {
fetchController.abort()
}
});最終效果
圖片

2.10 空閑時(shí)間執(zhí)行任務(wù)
利用瀏覽器空閑期執(zhí)行低優(yōu)先級(jí)任務(wù)(如日志上報(bào)、預(yù)加載),避免阻塞主線程,優(yōu)化頁(yè)面響應(yīng)速度,提升用戶交互流暢度。
HTML頁(yè)面
<div class="api-section">
<h2>10. requestIdleCallback</h2>
<p>在瀏覽器空閑時(shí)執(zhí)行任務(wù)</p>
<button id="idleTaskBtn" class="btn">安排空閑任務(wù)</button>
<div id="idleOutput" class="output"></div>
</div>JavaScript實(shí)現(xiàn)
const tasks = ['任務(wù)1', '任務(wù)2', '任務(wù)3', '任務(wù)4', '任務(wù)5']
document.querySelector('#idleTaskBtn').addEventListener('click', () => {
const output = document.getElementById('idleOutput')
output.textContent = '已安排空閑任務(wù)...'
function executeTasks(deadline) {
while ((deadline.timeRemaining() > 0 || deadline.didTimeout) && tasks.length > 0) {
const task = tasks.pop()
output.textContent += `\n執(zhí)行: ${task}`
// 模擬任務(wù)耗時(shí)
const start = performance.now()
while (performance.now() - start < 50) {}
}
if (tasks.length > 0) {
requestIdleCallback(executeTasks, { timeout: 1000 })
} else {
output.textContent += '\n所有任務(wù)完成!'
}
}
requestIdleCallback(executeTasks, { timeout: 1000 })
})最終效果
































