Web Design
Mobile Internet
Brand Design
Innovative
News
Encyclopedias

How to replace Jquery with javascript in website production

Date:2016-04-29 Source: Shangpin China Type: website encyclopedia
Word Size: small   medium   big

JQuery is the most popular JavaScript tool library.

According to statistics, it is currently used by 57.3% of websites around the world. In other words, 6 of the 10 websites use jQuery. If you only investigate the Website production This proportion will rise to an astonishing 91.7%.

  JQuery is the most popular JavaScript tool library

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, requires 1 second or more to fully load, not to mention mobile devices. This means that if you use jQuery, users will be delayed at least 1 second to see the web page effect. Considering that jQuery is essentially just a tool for operating DOM, we should not only ask: if it is only for a few special effects of web pages, is it necessary to use such a large library?

When jQuery was born in 2006, it was mainly used to eliminate the differences between different browsers (mainly IE6) and provide a simple and unified interface for developers. Compared with that time, today's situation has changed a lot. IE's market share is declining, and the standard JavaScript syntax based on ECMAScript is getting more and more support. Developers can run in all major browsers at the same time by directly using the JavScript standard syntax, and no longer need to obtain compatibility through jQuery.

Now we will discuss how to use JavaScript standard syntax to replace some main functions of jQuery and achieve jQuery free.

 jQuery-free

1、 Select DOM element

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

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

It should be noted here that the querySelectorAll method returns a NodeList object, which is much like an array (with numeric index and length properties), but it is not an array. You cannot use pop, push and other array specific methods. If necessary, consider converting Nodelist objects into arrays.

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

2、 DOM Operation

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

Add DOM element at the end.

  1. //JQuery writing method
  2. $(parent).append($(child));  
  3.  
  4. //DOM writing
  5. parent.appendChild(child) 

The header inserts a DOM element.

  1. //JQuery writing method
  2. $(parent).prepend($(child));  
  3.  
  4. //DOM writing
  5. parent.insertBefore(child, parent.childNodes[0]) 

Delete the DOM element.

  1. //JQuery writing method
  2. $(child).remove()  
  3.  
  4. //DOM writing
  5. child.parentNode.removeChild(child) 

3、 Event monitoring

The on method of jQuery can be completely simulated with addEventListener.

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

For convenience, you can also deploy this method on the NodeList object.

  1. NodeList.prototype.on = function (event, fn) {  
  2. []['forEach'].call(this, function (el) {  
  3. el.on(event, fn);  
  4. });  
  5. return this;  
  6. };  

4、 Event triggering

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

  1. Element.prototype.trigger = function (type, data) {  
  2. var event = document.createEvent('HTMLEvents');  
  3. event.initEvent(type, true, true);  
  4. event.data = data || {};  
  5. event.eventName = type;  
  6. event.target = this;  
  7. this.dispatchEvent(event);  
  8. return this;  
  9. };  

Deploy this method on the NodeList object.

  1. NodeList.prototype.trigger = function (event) {  
  2. []['forEach'].call(this, function (el) {  
  3. el['trigger'](event);  
  4. });  
  5. return this;  
  6. };  

5、 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 as $(function)) is unnecessary, because the DOM object has been generated by the time of running.

6、 Attr method

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

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

DOM elements allow direct reading of attribute values, and the writing method is much simpler.

  1. $("#picture").src = " //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 exact attribute values of these two web page elements, you can use this. getAttribute ('value ') and this. getAttribute ('href').

7、 AddClass method

The addClass method of jQuery is used to add a class for DOM elements.

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

The DOM element itself has a read-write className attribute, which can be used to operate on the class.

  1. document.body.className = 'hasJS';  
  2. // or  
  3. document.body.className += ' hasJS';  

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

  1. document.body.classList.add('hasJS');  
  2. document.body.classList.remove('hasJS');  
  3. document.body.classList.toggle('hasJS');  
  4. document.body.classList.contains('hasJS');  

8、 CSS

The css method of jQuery is used to set the style of web page elements.

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

DOM elements have a style attribute, which can be operated directly.

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

9、 Data storage

The jQuery object can store data.

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

HTML 5 has a dataset object and similar functions (not supported by IE 10), but only strings can be saved.

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

10、 Ajax

The Ajax method of jQuery is used for asynchronous operations.

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

We can define a request function to simulate Ajax methods.

  1. function request(type, url, opts, callback) {  
  2. var xhr = new XMLHttpRequest();  
  3. if (typeof opts === 'function') {  
  4. callback = opts;  
  5. opts = null;  
  6. }  
  7. xhr.open(type, url);  
  8. var fd = new FormData();  
  9. if (type === 'POST' && opts) {  
  10. for (var key in opts) {  
  11. fd.append(key, JSON.stringify(opts[key]));  
  12. }  
  13. }  
  14. xhr.onload = function () {  
  15. callback(JSON.parse(xhr.response));  
  16. };  
  17. xhr.send(opts ? fd : null);  

Then, based on the request function, simulate the get and post methods of jQuery.

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

11、 Animation

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

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

The animation effect of jQuery is mostly based on DOM. But at present, CSS 3 animation is far more powerful than DOM, so you can write animation effects into CSS, and then display animation by operating the class of DOM elements.

  1. foo.classList.add('animate');  

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

  1. el.addEventListener("webkitTransitionEnd", transitionEnded);  
  2.  
  3. el.addEventListener("transitionend", transitionEnded);  

12、 Alternatives

Because jQuery is too large, there are endless alternatives.

Among them, the most famous is zepto.js. Its design goal is to maximize the compatibility of jQuery APIs with the smallest volume. The original size of zepto.js version 1.0 is 55KB, the optimized size is 29KB, and the gzip compressed size is 10KB.

If you only want to simulate the basic functions of jQuery without seeking maximum compatibility, then min.js is only 200 bytes after optimization, while dolla is 1.7 KB after optimization.

In addition, jQuery itself adopts module design, and you can only choose to use the modules you need. See its github website for details, or use a dedicated Web interface.



Please contact our consultant

+86 10-60259772

Please provide your contact number. The project manager of shangpin China will contact you as soon as possible.