我相信我们都看过 site for vanilla-js (最快的 JavaScript 框架);D 我只是好奇,在为单击添加事件处理程序时,纯 JavaScript 到底比 jQuery 快多少。所以我前往 jsPerf 进行测试,我是 quite surprised by the results .
jQuery 优于纯 JavaScript 2500%。
我的测试代码:
//jQuery
$('#test').click(function(){
console.log('hi');
});
//Plain JavaScript
document.getElementById('test').addEventListener('click', function(){
console.log('hi');
});
我只是不明白这是怎么发生的,因为看起来 jQuery 最终将不得不使用与纯 JavaScript 使用的完全相同的函数。 谁能解释一下为什么我会这样?
最佳答案
正如您在 jQuery.event.add 的这段代码中看到的,它只创建了一次 eventHandle。
查看更多:http://james.padolsey.com/jquery/#v=1.7.2&fn=jQuery.event.add
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if (!events) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if (!eventHandle) {
elemData.handle = eventHandle = function (e) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply(eventHandle.elem, arguments) : undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
这里我们有 addEventListener:
// Init the event handler queue if we're the first
handlers = events[type];
if (!handlers) {
handlers = events[type] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) {
// Bind the global event handler to the element
if (elem.addEventListener) {
elem.addEventListener(type, eventHandle, false);
} else if (elem.attachEvent) {
elem.attachEvent("on" + type, eventHandle);
}
}
}
关于javascript - jQuery 的 click() 函数怎么会比 addEventListener() 快这么多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13407960/