Today's Question:  What does your personal desk look like?        GIVE A SHOUT

How to be jQuery-free?

  é˜®ä¸€å³°        2013-05-13 11:53:20       6,618        0    

jQuery is now the most famous JavaScript library. There are around 57.3% websites in the world using jQuery, i.e, 6 out of 10 websites are using jQuery. If we only consider those websites which use libraries, then the percentage is even higher which is 91.7%.

Although jQuery is very popular, its size is still a headache to many websites maintainers. The uncompressed jQuery 2.0 has a size of 235KB, the size is 81KB after optimization.The jQuery 1.8.3 which supports IE 6/7/8 has a uncompressed size of 261KB, the size is 91KB after optimization.

It takes around 1 second to load this file, it may take even longer on mobile devices. This means if you use jQuery in your website, users may be delayed by 1 second to view the webpage effect. In fact, jQuery is just a tool to handle DOM. There is one question we may ask, do we really need to use a library with this size to show some cool effects on some pages?

In 2006, when jQuery was born, it was mainly used to eliminate the incompatibilities among different browsers, it provides a common interface for developers. Compared to 2006, the current situation is much different. The market share of IE keeps decline, the standard JavaScript syntax based on ECMAScript is becoming more and more widely supported. Now developers can get the scripts running on many web browsers with the ECMAScript syntax.

So now we introduce some JavaScript standard syntax to replace some jQuery functions so that our websites can be jQuery-free.

1. Select DOM element

The core of jQuery is to select DOM select with selectors, we can use querySelectorAll method to simulate this function.

var $ = document.querySelectorAll.bind(document);

The querySelectorAll method returns a NodeList object, it's similar to an array but not an array. It's indexed and has a length property. We cannot apply pop,push on it. If necessary, we can convert NodeList into an array.

myList = Array.prototype.slice.call(myNodeList);

2. DOM operation

There are many method can be used to operate DOM elements.

Append DOM element:

//In jQuery
$(parent).append($(child));
//In DOM
parent.appendChild(child)

Prepend DOM element:

//In jQuery
$(parent).prepend($(child));
//In DOM
parent.insertBefore(child, parent.childNodes[0])

Remove DOM element

//In jQuery
$(child).remove()
//In DOM
child.parentNode.removeChild(child)

3. Event listener

The on method in jQuery can be simulated using addEventListener

Element.prototype.on = Element.prototype.addEventListener;

To ease the use, we can implement this method on NodeList object

NodeList.prototype.on = function (event, fn) {
   []['forEach'].call(this, function (el) {
      el.on(event, fn);
   });
   return this;
};

4. Trigger event

The trigger method in jQuery needs to be separately implemented. It's a bit complicated:

Element.prototype.trigger = function (type, data) {
    var event = document.createEvent('HTMLEvents');
    event.initEvent(type, true, true);
    event.data = data || {};
    event.eventName = type;
    event.target = this;
    this.dispatchEvent(event);
    return this;
};

We need to deploy this method on NodeList object as well:

NodeList.prototype.trigger = function (event) {
    []['forEach'].call(this, function (el) {
      el['trigger'](event);
    });
    return this;
};

5. document.ready

The best practice as of now is to load the JavaScript at the bottom of a webpage. In this manner, the document.ready function is not necessary anymore.

6. attr method

jQuery uses attr method to read element's attributes.

$("#picture").attr("src", "http://url/to/image");

DOM elements allow directly access attribute.

$("#picture").src = "http://url/to/image";

this.value in input elements will return the values in the input text field; this.href in a link element will return the absolute URL. If you want to get the exact values in these two elements, please use this.getAttribute("value") and this.getAttribute("href");

7. addClass method

addClass method in jQuery is to add one class to a DOM element.

$('body').addClass('hasJS');

DOM has a property className which can be used to read and write class.

document.body.className = 'hasJS';
// or
document.body.className += ' hasJS';

HTML5 provides a classList object which is more powerful.

document.body.classList.add('hasJS');
document.body.classList.remove('hasJS');
document.body.classList.toggle('hasJS');
document.body.classList.contains('hasJS');

8. CSS

css method in jQuery is to set style of DOM element

$(node).css( "color", "red" );

DOM element has a style property.

element.style.color = "red";;
// or
element.style.cssText += 'color:red';

9. Data storage

jQuery object can store data

$("body").data("foo", 52);

HTML5 has a dataset object which has similar functions. But it can only stores strings.

element.dataset.user = JSON.stringify(user);
element.dataset.score = score;

10. AJAX

jQuery has an ajax method

$.ajax({
    type: "POST",
    url: "some.php",
    data: { name: "John", location: "Boston" }
}).done(function( msg ) {
    alert( "Data Saved: " + msg );
});

We can define a request function to simulate ajax

function request(type, url, opts, callback) {
    var xhr = new XMLHttpRequest();
    if (typeof opts === 'function') {
      callback = opts;
      opts = null;
    }
    xhr.open(type, url);
    var fd = new FormData();
    if (type === 'POST' && opts) {
      for (var key in opts) {
        fd.append(key, JSON.stringify(opts[key]));
      }
    }
    xhr.onload = function () {
      callback(JSON.parse(xhr.response));
    };
    xhr.send(opts ? fd : null);
}

Then we can simulate get and post method based on request method

var get = request.bind(this, 'GET');
var post = request.bind(this, 'POST');

11. Animation

jQuery has animate method to generate animation effect

$foo.animate('slow', { x: '+=10px' })ï¼›

Animation effect in jQuery are mainly based on DOM. CSS3 provides more powerful animation functions than DOM. Hence we can write the animation effects into CSS, then we can change the animation by changing the class of DOM elements

foo.classList.add('animate')ï¼›

If we want to pass callback functions, CSS3 has some events.

el.addEventListener("webkitTransitionEnd", transitionEnded);
el.addEventListener("transitionend", transitionEnded);

12. Backup plan

There are many substitutions to jQuery due to large size of jQuery. The most famous among them is zepto.js.

13. References

- Remy Sharp,I know jQuery. Now what? 
- Hemanth.HM,Power of Vanilla JS
- Burke Holland,5 Things You Should Stop Doing With jQuery

Author : é˜®ä¸€å³° Source : http://www.ruanyifeng.com/blog/2013/05/jquery-free.html

JAVASCRIPT  JQUERY  CSS3  ECMASCRIPT 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.