Using JS standard syntax instead of JS Tool library jquery function

Source: Internet
Author: User
Tags add foreach array object bind interface json key

Article Introduction: How the site does not need jquery at all.

JQuery is now the most popular JavaScript tool library.

According to statistics, currently 57.3% of the world's web sites use it. In other words, 10 sites, 6 use jquery. If you only look at sites that use the tool library, the percentage will rise to a staggering 91.7%.

While jquery is so popular, its bloated size is a 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.

Such a volume, even in a broadband environment, it takes 1 seconds or more to complete the load, not to mention mobile devices. This means that if you use jquery, the user can delay at least 1 seconds to see the page effect. As a matter of fact, jquery is just a tool for manipulating the DOM, and we have to ask: is it necessary to use such a large library for only a few web effects?

When JQuery was born in 2006, it was designed to eliminate differences in browsers (primarily IE6), providing a concise, unified interface for developers. Today's situation has changed a lot compared to the time. With the declining market share of IE, the JavaScript standard syntax based on ECMAScript is getting more and more extensive support. Developers use the Javscript standard syntax directly, they can run at the same time in each big browser, no longer need to get compatibility through jquery.

Here's how to use JavaScript standard syntax to replace some of jquery's main features 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);


Note here that the Queryselectorall method returns a NodeList object that is much like an array (with numeric indexes and length attributes), 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 way jquery provides it.

The tail appends the DOM element.

jquery notation

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

Dom notation

Parent.appendchild (Child)

Inserts a DOM element into the head.


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 completely 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 requires a separate deployment, which 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;

};

Five, Document.ready

The current best practice is to load JavaScript script files at the bottom of the page. In this case, the Document.ready method (jquery is abbreviated to $ (function)) is unnecessary, because the DOM object has already 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 you to read attribute values directly, much simpler.

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

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 value of the attributes for both page elements.

Vii. Methods of AddClass

The AddClass method of jquery, which is used to add a class to the DOM element.

$ ("Body"). AddClass ("Hasjs");

The DOM element itself has a read-write classname attribute 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 is used to set the style of the page elements.

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

The DOM element has a style attribute 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 strings can be saved.

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

Element.dataset.score = score;

Ten, Ajax

The AJAX approach to jquery 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 to simulate AJAX methods.

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, simulate the get and post methods of jquery.

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

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

Xi. Animation

The animate method of jquery, which is used to generate animation effects.

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

The animation effect of jquery is largely based on DOM. But for now, CSS 3 animations are far more powerful than DOM, so you can write animation effects into CSS, and then manipulate the DOM element class to show the animation.

Foo.classList.add ("animate");

If you need to use callback functions for animations, CSS 3 also defines the corresponding events.

El.addeventlistener ("Webkittransitionend", transitionended);

El.addeventlistener ("Transitionend", transitionended);

12. Alternative Solutions

Because of the large size of jquery, alternative solutions are emerging.

Among them, the most famous is the zepto.js. Its design goal is to achieve maximum compatibility with the jquery 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 seek maximum compatibility, only want to simulate the basic functionality of jquery, then min.js optimized only 200 bytes, and Dolla optimized is 1.7KB.

In addition, jquery itself uses modular design, and can only choose to use its own modules. See its GitHub Web site, or use a dedicated web interface.

13, reference links

    1. -Remy sharp,i know jQuery. Now what?
    2. -Hemanth.hm,power of Vanilla JS
    3. -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.