旧版浏览器需回退到document.createevent('customevent') + initcustomevent()创建自定义事件;先检测customevent构造函数是否可用,不可用则用传统api模拟,注意ie9–ie10不支持null/undefined/detail中含函数或dom节点。

在旧版浏览器(如 IE9–IE11、部分 Android 4.x WebView)中,CustomEvent 构造函数不可用或行为不一致,此时需回退到 document.createEvent('CustomEvent') + initCustomEvent() 方式来创建和派发兼容的自定义事件。
判断并创建 CustomEvent 实例
先检测原生 CustomEvent 是否可用;若不支持,则用传统 DOM Event API 模拟:
- 调用
document.createEvent('CustomEvent')创建事件对象 - 再调用
initCustomEvent(type, bubbles, cancelable, detail)初始化它 -
type:事件名(字符串),如'my-event' -
bubbles:是否冒泡(布尔值) -
cancelable:是否可取消(布尔值) -
detail:附带的任意数据(通常为对象,旧版中建议避免函数/undefined/null)
完整兼容写法示例
以下是一个可在 IE9+ 安全运行的封装函数:
function createCustomEvent(type, bubbles, cancelable, detail) {
let event;
if (typeof CustomEvent === 'function') {
// 现代浏览器:直接构造
event = new CustomEvent(type, { bubbles, cancelable, detail });
} else {
// 旧版 IE/Android:回退方案
event = document.createEvent('CustomEvent');
event.initCustomEvent(type, bubbles, cancelable, detail);
}
return event;
}
// 使用示例
const myEvent = createCustomEvent('data-loaded', true, false, { id: 123, status: 'success' });
element.dispatchEvent(myEvent);
注意事项与常见坑点
initCustomEvent 在 IE 中对 detail 的处理较严格:
- IE9–IE10 不支持传入
null或undefined作为detail,会报错;建议默认传{} - IE 不支持在
detail中传函数或 DOM 节点(可能引发异常),只推荐基础类型或纯对象 -
createEvent('CustomEvent')在 IE9+ 可用,但 IE8 及更早版本不支持 —— 如需支持 IE8,需改用createEvent('Event')并手动挂载detail属性(非标准,仅作降级) - 确保目标元素已存在于 DOM 中,否则
dispatchEvent无效
简单 polyfill 建议(按需引入)
若项目需全局修复,可轻量 patch CustomEvent:
if (typeof CustomEvent !== 'function') {
window.CustomEvent = function(type, params) {
const event = document.createEvent('CustomEvent');
const bubbles = !!(params && params.bubbles);
const cancelable = !!(params && params.cancelable);
const detail = (params && params.detail !== undefined) ? params.detail : null;
// IE9+ 允许 detail 为 null,但稳妥起见可转为 {}
event.initCustomEvent(type, bubbles, cancelable, detail || {});
return event;
};
}
这样后续代码可统一使用 new CustomEvent(...),无需每次判断。










