Reduce jquery Volume

Source: Internet
Author: User

JQuery Analysis

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 significantly compared to that time (usage share of web browsers). 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.

Select 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);
这里需要注意的是,querySelectorAll方法返回的是NodeList对象,它很像数组(有数字索引和length属性),但不是数组,不能使用pop、push等数组特有方法。如果有需要,可以考虑将Nodelist对象转为数组。
MyList = Array.prototype.slice.call (mynodelist);
DOM Operations

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)
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.

function  (event, FN) {[]' ForEach '].call (thisfunction  (EL) {El.on (event, FN);  });  returnthis;};

Triggering of events

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

function (type, data) {  var event = document.createevent (' htmlevents 'truetrue  = Data | |   =this;   this. Dispatchevent (event);  returnthis;};

This method is also deployed on the NodeList object.

function  (event) {[] [' ForEach '].call(thisfunction  (EL) {el[' trigger ')(event);  });  returnthis;};

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.

Attr method

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 this.value returns the value in the input box, and the this.href of the link element returns an absolute URL. If you need to use the exact values of the attributes of these two page elements, you can use the this.getAttribute(‘value‘)和this.getAttibute(‘href‘) .

AddClass method

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 ');d ocument.body.classList.remove (' Hasjs '); Document.body.classList.toggle (' Hasjs ');d ocument.body.classList.contains (' Hasjs ');   
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";; // orElement.style.cssText + = ' color:red ';
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 == score;
Ajax

JQuery's Ajax method, used for asynchronous operations.

"POST""some.php" "John", Location: "Boston" }). Done (function"Data  Saved: "+ msg); });

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

functionrequest (type, URL, opts, callback) {varXHR =NewXMLHttpRequest (); if(typeofopts = = = ' function ') {Callback=opts; OPTs=NULL;  } xhr.open (type, URL); varFD =NewFormData (); if(Type = = = ' POST ' &&opts) { for(varKeyinchopts)    {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 ');
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);
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

Reduce jquery Volume

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.