我敢肯定我们都看过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/