JQuery is not required for websites, but can also meet simple requirements.

Source: Internet
Author: User

JQuery is now the most popular JavaScript tool library.

According to statistics, 57.3% of websites around the world are currently using it. That is to say, six of the 10 websites use jQuery. If you only look at the websites using the tool library, this proportion will rise to an astonishing 91.7%.

Although jQuery is so popular, its bloated size is also a headache. The original size of jQuery 2.0 is 235KB, and the optimized size is 81KB. For jQuery 1.8.3 that supports IE6, 7, and 8, the original size is 261KB, and the optimized size is 91KB.

Such a volume, even in a broadband environment, takes 1 second or longer to fully load, let alone mobile devices. This means that if you use jQuery, the user will delay at least one second to see the webpage effect. Considering that jQuery is only a tool for DOM operations, we should not only ask: is it necessary to use such a large library for a few special webpage effects?

When jQuery was born in 2006, it was mainly used to eliminate the differences between different browsers (mainly IE6) and provide developers with a simple and unified interface. Today, the situation has changed a lot. The market share of IE is declining. The standard JavaScript syntax based on ECMAScript is becoming more and more widely supported. Developers can directly use the JavScript standard syntax to run in various browsers at the same time, without the need to obtain compatibility through jQuery.

Next we will discuss how to use JavaScript standard syntax to replace some of jQuery's main functions and implement jQuery-free.

1. Select DOM elements

The core of jQuery is to use various selectors to select DOM elements. You can use querySelectorAll to simulate this function.

Copy codeThe Code is as follows: var $ = document. querySelectorAll. bind (document );

It should be noted that the querySelectorAll method returns the NodeList object, which is similar to an array (which has the numeric index and length attributes), but is not an array. It cannot use pop, push, and other array-specific methods. If necessary, convert the Nodelist object into an array.

Copy codeThe Code is as follows: myList = Array. prototype. slice. call (myNodeList );

Ii. DOM operations

DOM itself has a wealth of operation methods, which can replace the operation methods provided by jQuery.

Append the DOM element to the end.

Copy codeThe Code is as follows:
// JQuery Writing Method
$ (Parent). append ($ (child ));
// DOM writing
Parent. appendChild (child)

Insert DOM elements in the header.

Copy codeThe Code is as follows:
// JQuery Writing Method
$ (Parent). prepend ($ (child ));
// DOM writing
Parent. insertBefore (child, parent. childNodes [0])

Delete a dom element.

Copy codeThe Code is as follows:
// JQuery Writing Method
$ (Child). remove ()
// DOM writing
Child. parentNode. removeChild (child)

Iii. event monitoring

The on method of jQuery can be simulated using addEventListener.

Copy codeThe Code is as follows: Element. prototype. on = Element. prototype. addEventListener;

For ease of use, you can also deploy this method on the NodeList object.

Copy codeThe Code is as follows: NodeList. prototype. on = function (event, fn ){
[] ['Foreach']. call (this, function (el ){
El. on (event, fn );
});
Return this;
};

Iv. event triggering

The trigger method of jQuery needs to be deployed separately, which is relatively complicated.

Copy codeThe Code is as follows:
Element. prototype. trigger = function (type, data ){
Var event = document. createEvent ('htmlevents ');
Event. initEvent (type, true, true );
Event. data = data {};
Event. eventName = type;
Event.tar get = this;
This. dispatchEvent (event );
Return this;
};

This method is also deployed on the NodeList object.

Copy codeThe Code is as follows:
NodeList. prototype. trigger = function (event ){
[] ['Foreach']. call (this, function (el ){
El ['trigger'] (event );
});
Return this;
};

V. document. ready

The best practice is to load all JavaScript script files at the bottom of the page. In this case, the document. ready method (jQuery is abbreviated as $ (function) is unnecessary because the DOM object has been generated by running.

Vi. attr Method

JQuery uses the attr method to read and write the attributes of webpage elements.

Copy codeThe Code is as follows: $ ("# picture"). attr ("src", "http: // url/to/image ");

DOM elements allow direct reading of attribute values, which are much simpler in writing.

Copy codeThe Code is as follows: $ ("# picture"). src = "http: // url/to/image ";

Note that this. value of the input element returns the value in the input box, And this. href of The Link element returns the absolute URL. If you need to use the correct attribute values of these two web page elements, you can use this. getAttribute ('value') and this. getattivity ('href ').

VII. addClass Method

JQuery's addClass method is used to add a class to the DOM element.

Copy codeThe Code is as follows:
$ ('Body'). addClass ('hasjs ');

The DOM element itself has a read/write className attribute that can be used to operate classes.

Copy codeThe Code is as follows:
Document. body. className = 'hasjs ';
// Or
Document. body. className + = 'hasjs ';

HTML 5 also provides a classList object, which is more powerful (not supported by IE 9 ).

Copy codeThe Code is as follows:
Document. body. classList. add ('hasjs ');
Document. body. classList. remove ('hasjs ');
Document. body. classList. toggle ('hasjs ');
Document. body. classList. contains ('hasjs ');

VIII. CSS

JQuery's css method is used to set the style of webpage elements.

Copy codeThe Code is as follows: $ (node). css ("color", "red ");

The DOM element has a style attribute and can be operated directly.

Copy codeThe Code is as follows:
Element. style. color = "red ";;
// Or
Element.style.css Text + = 'color: red ';

9. Data Storage

JQuery objects can store data.

Copy codeThe Code is as follows: $ ("body"). data ("foo", 52 );

HTML 5 has a dataset object and has similar functions (not supported by IE 10). However, it can only save strings.

Copy codeThe Code is as follows:
Element. dataset. user = JSON. stringify (user );
Element. dataset. score = score;

10. Ajax

JQuery Ajax Method for asynchronous operations.

Copy codeThe Code is as follows:
$. 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 the Ajax method.

Copy codeThe Code is as follows:
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, the get and post methods of jQuery are simulated based on the request function.

Copy codeThe Code is as follows:
Var get = request. bind (this, 'get ');
Var post = request. bind (this, 'post ');



11. Animation

JQuery's animate method is used to generate animation effects.

Copy codeThe Code is as follows: $ foo. animate ('slow', {x: '+ = 10px '});

Most of jQuery's animation effects are based on DOM. However, currently, CSS 3 is far more powerful than DOM, so you can write the animation effect into CSS and then demonstrate the animation by operating the class of DOM elements.

Copy codeThe Code is as follows: foo. classList. add ('animate ');

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

Copy codeThe Code is as follows:
El. addEventListener ("webkitTransitionEnd", transitionEnded );
El. addEventListener ("transitionend", transitionEnded );

12. Alternative Solutions

Because jQuery is too large, there are endless alternatives.

Zepto. js is the most famous among them. Its design goal is to minimize the volume and achieve maximum compatibility with jQuery APIs. The original size of zepto. js 1.0 is 55 KB, the optimized size is 29KB, And the gzip compressed size is 10 KB.

If you do not require maximum compatibility and only want to simulate basic functions of jQuery, min. js is optimized to 200 bytes, while dolla is optimized to 1.7KB.

In addition, jQuery uses the module design. You can select only the modules you need. For more information, see its GitHub website or use a dedicated Web interface.

XIII. Reference Links

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

(End)

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.