兼容策略

采用合理的兼容策略可以减少兼容性问题的工作量。

兼容策略对比

策略 说明 适用场景
渐进增强 先满足基础需求,再增强功能 新功能、低版本浏览器
优雅降级 先实现完整功能,再处理兼容 复杂交互、旧浏览器
特性检测 检测API/属性是否存在 JS API兼容
CSS前缀 添加浏览器前缀 CSS新属性
Polyfill 引入兼容垫片 缺失的JS API

兼容处理示例

// 1. 特性检测
if ('fetch' in window) {
    // 使用fetch
} else {
    // 使用XMLHttpRequest
}

// 2. Polyfill示例
if (!typeof Promise.allSettled) {
    Promise.allSettled = function(promises) {
        return Promise.all(promises.map(async p => {
            try {
                const value = await p;
                return { status: 'fulfilled', value };
            } catch(reason) {
                return { status: 'rejected', reason };
            }
        }));
    };
}

// 3. CSS前缀处理
.flex-container {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
}

// 4. 事件兼容
const supportTouch = 'ontouchstart' in window;
const eventType = supportTouch ? 'touchstart' : 'click';

// 5. 动画兼容
const supportAnimation = typeof AnimationEvent !== 'undefined';
const animationEndEvent = supportAnimation 
    ? 'animationend' 
    : 'webkitAnimationEnd';
← Device Difference Device Examples →