How to do as much as possible without using the huge jquery

Source: Internet
Author: User

JQuery is now the most popular JavaScript tool library.

According to statistics, currently 57.3% of the world's websites use it. That is, there are 6 of the 10 sites that use JQuery. If you only look at sites that use the tool library, this ratio will rise to a staggering 91.7%.

Although JQuery is so popular, its bloated size also makes people feel headache. The original size of jquery 2.0 is 235KB, optimized for 81KB, and if it is a jquery 1.8.3 that supports IE6, 7, 8, the original size is 261KB and is optimized for 91KB.

This volume, even in a broadband environment, takes 1 seconds or longer to fully load, not to mention mobile devices. This means that if you use JQuery, the user will be delayed for at least 1 seconds to see the page effect. Given that JQuery is essentially a tool for manipulating the DOM, we have to ask: is it necessary to use such a large library for only a few web effects?

In the 2006, when JQuery was born, it was used primarily to eliminate differences between browsers (mainly IE6), providing developers with a simple, unified interface. Today's situation has changed a lot compared to that time. IE's market share is declining, and the ECMAScript-based JavaScript standard syntax is getting more and more widely supported. By using Javscript standard syntax directly, developers can run in large browsers at the same time, eliminating the need for compatibility through jQuery.

Here's how to use JavaScript standard syntax to replace some of the main features of JQuery and do jquery-free.

First, select the DOM element

At the heart of JQuery is the selection of DOM elements through various selectors, which can be simulated using the Queryselectorall method.

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

It is important to note that the Queryselectorall method returns the NodeList object, which is much like an array (with a numeric index and a length property), but not an array, and cannot use an array-specific method such as pop, push, and so on. If necessary, consider converting the Nodelist object to an array.

MyList = Array.prototype.slice.call (mynodelist);

Second, DOM operation

The DOM itself has a rich way of doing things that can replace the operation methods provided by JQuery.

Appends the DOM element to the tail.

JQuery notation

$ (parent). Append ($ (child));

DOM notation

Parent.appendchild (Child)

The head is inserted into the DOM element.

JQuery notation

$ (parent). Prepend ($ (child));

DOM notation

Parent.insertbefore (Child, Parent.childnodes[0])

Deletes a DOM element.

JQuery notation

$ (Child). Remove ()

DOM notation

Child.parentNode.removeChild (Child)

iii. monitoring of events

The on method of jQuery can be fully simulated with AddEventListener.

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

This method can also be deployed on NodeList objects for ease of use.

NodeList.prototype.on = function (event, FN) {

[] [' ForEach '].call (this, function (EL) {

El.on (event, FN);

});

return this;

};

Iv. triggering of events

The trigger method of jQuery needs to be deployed separately and is relatively complex.

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;

};

This method is also deployed on the NodeList object.

NodeList.prototype.trigger = function (event) {

[] [' ForEach '].call (this, function (EL) {

el[' Trigger '] (event);

});

return this;

};

Wu, Document.ready

The best practice now is to load JavaScript script files at the bottom of the page. In this case, the Document.ready method (JQuery shorthand is $ (function)) is not necessary because the DOM object has been generated when it is run.

Vi. Methods of attr

JQuery uses the Attr method to read and write properties of page elements.

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

DOM elements allow direct reading of property values, which is much more concise.

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

It is important to note that the INPUT element's This.value returns the value in the entry box, and the this.href of the link element returns an absolute URL. You can use This.getattribute (' value ') and This.getattibute (' href ') if you need to use the exact values of the attributes of these two page elements.

Vii. Methods of AddClass

JQuery's AddClass method, which is used to add a class to the DOM element.

$ (' body '). addclass (' Hasjs ');

The DOM element itself has a writable ClassName property that can be used to manipulate class.

Document.body.className = ' Hasjs ';

Or

Document.body.className + = ' Hasjs ';

HTML 5 also provides a Classlist object that is more powerful (IE 9 is not supported).

Document.body.classList.add (' Hasjs ');

Document.body.classList.remove (' Hasjs ');

Document.body.classList.toggle (' Hasjs ');

Document.body.classList.contains (' Hasjs ');

Eight, CSS

JQuery's CSS method, which sets the style of a page element.

$ (node). CSS ("Color", "red");

DOM elements have a style property that can be manipulated directly.

Element.style.color = "red";;

Or

Element.style.cssText + = ' color:red ';

ix. Data Storage

JQuery objects can store data.

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

HTML 5 has a DataSet object and similar functionality (IE 10 is not supported), but only the string is saved.

Element.dataset.user = json.stringify (user);

Element.dataset.score = score;

10. Ajax

JQuery's Ajax method, used for asynchronous operations.

$.ajax ({

Type: "POST",

URL: "some.php",

Data: {name: "John", Location: "Boston"}

}). Done (function (msg) {

Alert ("Data Saved:" + msg);

});

We can define a request function that simulates an Ajax method.

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, based on the request function, the Get and post methods of JQuery are simulated.

var get = Request.bind (this, ' get ');

var post = Request.bind (this, ' post ');

11. Animation

The animate method of JQuery, which is used to create animation effects.

$foo. Animate (' slow ', {x: ' +=10px '});

The animation effect of JQuery is largely based on the DOM. But currently, the animation of CSS 3 is far more powerful than DOM, so you can write animation effects into CSS and then display the animation by manipulating the DOM element's class.

Foo.classList.add (' animate ');

If you need to use a callback function for an animation, CSS 3 also defines the corresponding event.

El.addeventlistener ("Webkittransitionend", transitionended);

El.addeventlistener ("Transitionend", transitionended);

12. Alternative Solutions

Because of the large size of jQuery, alternative solutions abound.

Among them, the most famous is zepto.js. Its goal is to achieve the maximum compatibility with JQuery's API with minimal volume. Zepto.js 1.0 version of the original size is 55KB, optimized after 29kb,gzip compression for 10KB.

If you do not want maximum compatibility, only wish to emulate the basic functionality of JQuery, then min.js optimized only 200 bytes, and Dolla optimized is 1.7KB.

In addition, JQuery itself uses a modular design, which allows you to choose only the modules you need. Refer to its GitHub website, or use a dedicated web interface.

13. Reference Links

-Remy sharp,i know jQuery. What is now?

-Hemanth.hm,power of Vanilla JS

-Burke holland,5 things you should Stop Doing with JQuery

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.