JavaScript系列(76)--浏览器API深入
- 其他
- 2025-09-02 04:42:02

JavaScript浏览器API深入 🌐
浏览器提供了丰富的API,使JavaScript能够与浏览器环境进行交互。本文将深入探讨常用的浏览器API、最佳实践和性能优化技巧。
核心浏览器API 🌟💡 小知识:浏览器API是连接JavaScript与浏览器功能的桥梁,它们提供了操作DOM、处理事件、网络请求等能力。现代浏览器不断推出新的API,为开发者提供更强大的功能。
1. DOM操作API class DOMOperations { static demonstrateModernDOM() { // 现代选择器 const element = document.querySelector('.my-class'); const elements = document.querySelectorAll('.items'); // 元素遍历 const children = Array.from(element.children); const siblings = element.nextElementSibling; // DOM操作 const newElement = document.createElement('div'); element.append(newElement); element.remove(); // 属性操作 element.setAttribute('data-id', '123'); element.classList.add('active'); element.style.setProperty('--custom-color', 'red'); } static handleTemplates() { // 模板操作 const template = document.createElement('template'); template.innerHTML = ` <div class="card"> <h2></h2> <p></p> </div> `; const clone = template.content.cloneNode(true); document.body.appendChild(clone); } } 2. BOM操作API class BOMOperations { static demonstrateBOMFeatures() { // 窗口操作 const width = window.innerWidth; const height = window.innerHeight; // 视口信息 const viewportWidth = document.documentElement.clientWidth; const viewportHeight = document.documentElement.clientHeight; // 滚动操作 window.scrollTo({ top: 100, behavior: 'smooth' }); // 历史记录操作 window.history.pushState({ page: 1 }, 'title', '/new-url'); window.addEventListener('popstate', (event) => { console.log('返回到:', event.state); }); } static handleLocation() { // URL操作 const url = new URL(window.location.href); url.searchParams.set('page', '2'); history.pushState(null, '', url.toString()); } } 3. 网络请求API class NetworkOperations { static async demonstrateFetch() { // 基本GET请求 const response = await fetch('/api/data'); const data = await response.json(); // POST请求 const result = await fetch('/api/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: '张三' }) }); // 请求中断 const controller = new AbortController(); setTimeout(() => controller.abort(), 5000); try { const response = await fetch('/api/data', { signal: controller.signal }); } catch (error) { if (error.name === 'AbortError') { console.log('请求被取消'); } } } static async handleFormData() { const formData = new FormData(); formData.append('file', fileInput.files[0]); const response = await fetch('/api/upload', { method: 'POST', body: formData }); } } 现代浏览器API 📱 1. 观察者API class ObserverAPIs { static setupIntersectionObserver() { const observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { entry.target.classList.add('visible'); } }); }, { threshold: 0.5 }); document.querySelectorAll('.lazy-load') .forEach(el => observer.observe(el)); } static setupMutationObserver() { const observer = new MutationObserver((mutations) => { mutations.forEach(mutation => { if (mutation.type === 'childList') { console.log('子元素变化'); } }); }); observer.observe(document.body, { childList: true, subtree: true }); } static setupResizeObserver() { const observer = new ResizeObserver(entries => { entries.forEach(entry => { const { width, height } = entry.contentRect; console.log(`新尺寸: ${width} x ${height}`); }); }); observer.observe(document.querySelector('.responsive')); } } 2. 性能监控API class PerformanceAPIs { static measurePerformance() { // 性能标记 performance.mark('start'); // 执行一些操作... performance.mark('end'); performance.measure('操作耗时', 'start', 'end'); // 获取性能指标 const metrics = performance.getEntriesByType('measure'); console.log(metrics); } static monitorResources() { // 资源加载性能 const resources = performance.getEntriesByType('resource'); resources.forEach(resource => { console.log(`${resource.name}: ${resource.duration}ms`); }); } } 3. 媒体API class MediaAPIs { static async setupMediaRecorder() { const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true }); const recorder = new MediaRecorder(stream); const chunks = []; recorder.ondataavailable = (e) => chunks.push(e.data); recorder.onstop = () => { const blob = new Blob(chunks, { type: 'video/webm' }); const url = URL.createObjectURL(blob); // 处理录制的视频... }; recorder.start(); } static setupAudioContext() { const audioContext = new AudioContext(); const oscillator = audioContext.createOscillator(); const gainNode = audioContext.createGain(); oscillator.connect(gainNode); gainNode.connect(audioContext.destination); oscillator.type = 'sine'; oscillator.frequency.setValueAtTime(440, audioContext.currentTime); oscillator.start(); } } 存储API 💾 1. 本地存储 class StorageAPIs { static handleLocalStorage() { // 基本操作 localStorage.setItem('user', JSON.stringify({ name: '张三' })); const user = JSON.parse(localStorage.getItem('user')); // 存储事件监听 window.addEventListener('storage', (e) => { console.log('存储变化:', e.key, e.newValue); }); } static async handleIndexedDB() { const request = indexedDB.open('MyDB', 1); request.onupgradeneeded = (event) => { const db = event.target.result; const store = db.createObjectStore('users', { keyPath: 'id' }); store.createIndex('name', 'name', { unique: false }); }; request.onsuccess = (event) => { const db = event.target.result; const transaction = db.transaction(['users'], 'readwrite'); const store = transaction.objectStore('users'); store.add({ id: 1, name: '张三' }); }; } } 2. Cache API class CacheAPIs { static async handleCacheStorage() { // 缓存资源 const cache = await caches.open('v1'); await cache.add('/styles.css'); // 从缓存获取 const response = await cache.match('/styles.css'); // 缓存策略 async function fetchWithCache(request) { const cache = await caches.open('v1'); const cached = await cache.match(request); if (cached) { return cached; } const response = await fetch(request); await cache.put(request, response.clone()); return response; } } } 安全API 🔒 1. 权限API class SecurityAPIs { static async checkPermissions() { // 检查权限 const result = await navigator.permissions.query({ name: 'geolocation' }); switch (result.state) { case 'granted': console.log('已授权'); break; case 'prompt': console.log('需要请求权限'); break; case 'denied': console.log('已拒绝'); break; } } static async handleCredentials() { // 凭证管理 const credential = await navigator.credentials.create({ password: { id: 'user@example ', password: 'secretpassword' } }); // 存储凭证 await navigator.credentials.store(credential); } } 2. 内容安全 class ContentSecurity { static setupCSP() { // 在服务器端设置CSP头 // Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' // 报告违规 document.addEventListener('securitypolicyviolation', (e) => { console.log('CSP违规:', e.violatedDirective); }); } static handleCORS() { // 跨域请求 fetch(' api.example /data', { credentials: 'include', headers: { 'Content-Type': 'application/json' } }); } } 最佳实践 ⭐ 性能优化 class BrowserAPIBestPractices { static optimizeDOM() { // 使用文档片段 const fragment = document.createDocumentFragment(); for (let i = 0; i < 1000; i++) { const div = document.createElement('div'); fragment.appendChild(div); } document.body.appendChild(fragment); // 使用requestAnimationFrame function animate() { requestAnimationFrame(() => { // 执行动画 animate(); }); } } static optimizeStorage() { // 批量操作IndexedDB function batchAdd(items) { const transaction = db.transaction(['store'], 'readwrite'); const store = transaction.objectStore('store'); items.forEach(item => store.add(item)); return transaction plete; } } } 错误处理 class ErrorHandling { static async safeAPICall() { try { const result = await fetch('/api/data'); if (!result.ok) { throw new Error(`HTTP error! status: ${result.status}`); } return await result.json(); } catch (error) { console.error('API调用失败:', error); // 优雅降级处理 return null; } } } 特性检测 class FeatureDetection { static checkAPISupport() { if ('IntersectionObserver' in window) { // 使用IntersectionObserver } else { // 降级处理 } if ('serviceWorker' in navigator) { // 注册Service Worker } } } 性能考虑 ⚡ 避免频繁DOM操作 // 不推荐 for (let i = 0; i < 1000; i++) { document.body.appendChild(document.createElement('div')); } // 推荐 const fragment = document.createDocumentFragment(); for (let i = 0; i < 1000; i++) { fragment.appendChild(document.createElement('div')); } document.body.appendChild(fragment); 合理使用事件委托 document.querySelector('.list').addEventListener('click', (e) => { if (e.target.matches('.item')) { // 处理列表项点击 } }); 使用节流和防抖 function debounce(fn, delay) { let timer = null; return function (...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; } const handleResize = debounce(() => { // 处理窗口调整 }, 200); window.addEventListener('resize', handleResize); 总结 📝浏览器API提供了:
强大的DOM操作能力丰富的网络请求功能多样的存储选项现代化的观察者接口完善的安全机制💡 学习建议:
深入理解核心API的工作原理掌握现代浏览器新特性注意性能优化做好兼容性处理重视安全性考虑如果你觉得这篇文章有帮助,欢迎点赞收藏,也期待在评论区看到你的想法和建议!👇
终身学习,共同成长。
咱们下一期见
💻
JavaScript系列(76)--浏览器API深入由讯客互联其他栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“JavaScript系列(76)--浏览器API深入”
上一篇
Mathtype安装入门指南
下一篇
数据库提权总结