Don't miss new standard javascript APIs
The new javascript (1.6) provides many useful features, specially in DOM manipulation, but I noticed that jQuery uses really few of them.
For example, the feature
element.classList could be used in add/remove/toggle/hasClass like this:
- // When in 'use strict' mode, the first argument of call function cannot be null or undefined
- // so make it an empty string
- if (Object.prototype.toString.call(document.documentElement.classList || '') === '[object DOMTokenList]') {
- var methods = {
- addClass: 'add',
- removeClass: 'remove',
- toggleClass: 'toggle',
- hasClass: 'contains'
- };
- for (var name in methods) {
- jQuery.fn[name] = function(method) {
- return function(className) {
- return this.each(function() {
- this.classList[method](className);
- });
- }
- }(methods[name]);
- }
- }
- else {
- // current implementation of jQuery
- }
Yes I ormit many logic in those function like we can call addClass('a b c') with space-separated class list, but the core logic is there to utilize new feature in javascript 1.6 and surelly much quicker than the normal implementation.
In my Firefox 4.0 b11, when I run the code below for 100,000 times, my code is about 1 time faster than the normal jQuery one:
- var div = $('<div class="a b c d e f g"></div>').addClass('a b c d e f g');
- console.time('toggleClass');
- for (var i = 0; i < 100000; i++) {
- div.toggleClass('abc');
- }
- console.timeEnd('toggleClass');
- // jQuery: 1624ms
- // after replace jQuery's implementation: 862ms
Also, there are other new features such as Array.forEach / Object.keys can be utilized in jQuery
sorry for poor english
thanks